简体   繁体   English

在Javascript中使用闭包时,为什么mouseover事件不起作用?

[英]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.

相关问题 当我使用mouseover事件时,JavaScript剪贴板不起作用 - JavaScript clipboard doesn't work when I use the mouseover event 为什么javascript mouseover事件在Chrome中不起作用? - why javascript mouseover event doesn't work in chrome? Javascript:“鼠标悬停”和“鼠标悬停”事件处理程序有效,但当“鼠标悬停”被“单击”替换时“鼠标悬停”无法正常工作 - Javascript: "Mouseover" and "mouseout" event handlers work, but "mouseout" doesn't work properly when "mouseover" is replaced by "click" 为什么此javascript闭包无效? - Why doesn't this javascript closure work? 当DOM2“单击”事件可用于“鼠标悬停”时,为什么它不起作用? - Why doesn't a DOM2“click” event work, when it does work for “mouseover”? 当事件从“鼠标悬停”更改为“单击”时脚本不起作用 - Script doesn't work when event is changed from "mouseover" to "click" 当我更改函数的位置时,为什么不使用javascript闭包? - When i changed position of functions why doesn't it work with javascript closure? 为什么这个javascript闭包无法正常运行? - Why doesn't this javascript closure work as I hoped? 为什么一个JavaScript闭包工作而另一个没有? - Why does one JavaScript closure work and the other doesn't? 鼠标悬停事件不起作用(vanilla Javascript) - Mouseover event don't work (vanilla Javascript)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM