简体   繁体   English

Javascript关闭对点击事件的疑虑

[英]Javascript closure doubts for click event

My JS code :- 我的JS代码: -

 var ul = document.createElement("ul");
    for(var i=0; i<10; i++){
    var li= document.createElement("li");
    li.innerHTML='this is my li  '+ i+ '.';
    li.onclick = (function (){
        return (function (){
            alert(i);
        })
    })();
    ul.appendChild(li);
    }

    document.body.appendChild(ul);

Test code -- http://jsfiddle.net/VhfEh/112/ 测试代码 - http://jsfiddle.net/VhfEh/112/

Html View :- Html查看: -

this is my li 0.
this is my li 1.
this is my li 2.
this is my li 3.
this is my li 4.
this is my li 5.
this is my li 6.
this is my li 7.
this is my li 8.
this is my li 9.

When I am clicking on any of the li I am getting 10.. which is the max value of i or it is i++ value.. 当我点击任何的li我得到10 ..这是最大值i或者是i++价值..

I tried something but its not working ?? 我尝试了一些东西,但它没有工作?

Doubts :- 怀疑: -

  • Function with in a function is not Closure in JavaScript ? 函数中的函数不是JavaScript中的Closure吗?

  • Example I am using is the JavaScript Closure example ?? 我正在使用的示例是JavaScript Closure示例?

Thanks !! 谢谢 !!

You're really close; 你真的很亲密; you just forgot to set up and use a parameter with that anonymous function: 你只是忘了设置并使用该匿名函数的参数:

li.onclick = (function (i) {
    return (function (){
        alert(i);
    })
})(i);

The whole point of the immediately-executed function is to give each handler a private copy of the loop variable, so you have to actually pass it in as a parameter like that. 立即执行函数的重点是为每个处理程序提供循环变量的私有副本,因此您必须将其作为参数传递给它。

You are right about needing a closure. 你是否需要关闭是正确的。

You have to keep the i somewhere inside the closure that is created by the function body: 你必须将i保持在由函数体创建的闭包内的某个位置:

li.onclick = (function (){
    var localI = i;
    return (function (){
        alert(localI);
    })
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM