Javascript事件函数问题

Javascript event functions question

本文关键字:问题 函数 事件 Javascript      更新时间:2023-09-26

为什么当我像这样添加一个事件作为函数时:

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

它被立即执行(即使我没有将元素悬停)。

但是这个可以:

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

您正在将"onmouseover"属性设置为函数调用表达式:

的返回值
test.onmouseover = func(test);

"func(test)"调用函数"func()",就像在任何其他代码中一样。

你可以这样做:

test.onmouseover = func;

这将绑定事件处理程序而不调用"func()",但它不会安排传递额外的参数。edit哦,等等,这只是DOM元素本身。