开发者

Javascript event functions question

Why when I add an event as a function like this:

function func(arg) 
{
arg.style.marginLeft = "65px";
}
window.onload = function() {
var test = document.getElementById("aaa");
test.onmouseover = func(test);
}

It's been exec开发者_StackOverflow社区uted immediately (even if I do not hover the element).

But this one works:

window.onload = function() {
var test = document.getElementById("aaa");
test.onmouseover = function() {
           test.style.marginLeft = "65px";
      }
}


You're setting the "onmouseover" property to the return value of a function call expression:

test.onmouseover = func(test);

That "func(test)" calls the function "func()", just as it would in any other code.

You could instead do this:

test.onmouseover = func;

That will bind the event handler and not call "func()", but it won't arrange for the additional parameter to be passed. edit Oh wait that's just the DOM element itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜