3

我有一个对象列表,每个对象都有一个 .bullet,它是一个 SPAN。我想将跨度上的单击绑定到处理程序,而不是使用 jQuery 对跨度执行特定操作。我看到一些我不理解的行为,所以我希望有人能解释发生了什么。基本上,第一个代码示例有效:

for (var i = 0 ; i< length ; i++) {

            (function(){
                dataNode = dataNodeList[i];

                var handler = function(e) {

                    e.data.node.bullet.firstChild.nodeValue = "- ";


                };


                $(dataNode.bullet).on("click",{node:dataNode},handler);


            })();

        }

但是,第二个变体不起作用:

for (var i = 0 ; i< length ; i++) {

            (function(){
                dataNode = dataNodeList[i];

                var handler = function() {

                    dataNode.bullet.firstChild.nodeValue = "- ";


                };


                $(dataNode.bullet).on("click",handler);


            })();

        }

在第二个例子中,

dataNode.bullet.firstChild.nodeValue = "- ";

对我想要的 SPAN 的值没有影响。我希望 dataNode.bullet 仍然指向我想要更改的 SPAN,因为 JavaScript 关闭。那么,有人可以解释为什么会失败吗?谢谢。

4

1 回答 1

6

Try this:

for (var i = 0 ; i< length ; i++) {
    (function(index){
        var dataNode = dataNodeList[index];

        var handler = function() {
            dataNode.bullet.firstChild.nodeValue = "- ";
        };

        $(dataNode.bullet).on("click",handler);
    })(i);
}

The closure defines a new scope. This is necessary because your handler isn't called until after the loop has finished, so i is not part of the scope at the time it is called, or (in some cases) has the last possible value from the loop.

于 2012-09-19T17:47:10.980 回答