Javascript关闭点击事件的疑问

Jav*_*der 4 html javascript closures

我的 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);
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)

当我点击任何一个时,li我得到 10.. 这是最大值i或它的i++值..

我尝试了一些东西,但它不起作用?

疑问:-

  • 函数中的函数不是 JavaScript 中的闭包吗?

  • 我使用的示例是 JavaScript Closure 示例?

谢谢 !!

Poi*_*nty 5

你们真的很接近;您只是忘记设置并使用该匿名函数的参数:

li.onclick = (function (i) {
    return (function (){
        alert(i);
    })
})(i);
Run Code Online (Sandbox Code Playgroud)

立即执行函数的全部要点是为每个处理程序提供循环变量的私有副本,因此您必须将其作为参数实际传递。

  • @Neeraj我不确定我是否理解你的问题...是的,该代码创建了一个闭包,但问题是,如果不引入该参数(或类似Lee Meador的答案,这也应该有效),你就没有利用它闭包可以做什么。 (2认同)