[英]Why doesn't the mouseover event work when use closure in Javascript?
I have the following code 我有以下代码
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
var lists = document.getElementsByTagName("li");
for(var i=0, len = lists.length; i< len; i++){
lists[i].onmouseover = function(){
console.log(i);
}(i);
}
Expected result: when mouse over each li
, I got 0 or 1 or 2 or 3 in the console, but I only got those number when refresh the page not in mouseover
, anybody knows why? 预期结果:当鼠标悬停在每个
li
,我在控制台中得到0或1或2或3,但是在mouseover
没有刷新页面时才得到那些数字,有人知道为什么吗?
The "calling parenthesis" (i)
after the function expression execute the function immediately and assign its return value as event handler (which is undefined
). 函数表达式之后的“调用括号”
(i)
立即执行该函数,并将其返回值分配为事件处理程序( undefined
)。 Here is an example with a function declaration, which makes it easier to see (hopefully): 这是一个带有函数声明的示例,它使(希望)更容易看到:
function foo(i) {
console.log(i);
}
// in the loop
lists[i].onmouseover = foo(i);
See how foo
is called and the return value is assigned to lists[i].onmouseover
? 查看如何调用
foo
并将返回值分配给lists[i].onmouseover
吗?
You have to return a function from the immediately invoked function expression: 您必须从立即调用的函数表达式中返回一个函数:
lists[i].onmouseover = (function(i){
return function() {
console.log(i);
};
}(i));
or with a function declaration: 或带有函数声明:
function createHandler(i) {
return function() {
console.log(i);
};
}
// in the loop
lists[i].onmouseover = createHandler(i);
More info: JavaScript closure inside loops – simple practical example 更多信息: 循环内的JavaScript闭合–简单的实际示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.