jQuery事件处理程序的JavaScript关闭 [英] JavaScript closure for jQuery event handler

查看:71
本文介绍了jQuery事件处理程序的JavaScript关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of objects each of which has a .bullet which is a SPAN. I want to bind a click on the span to a handler than performs a certain action on the span using jQuery. I'm seeing some behavior I don't understand, so I'm hoping someone can explain what's going on. Basically, this first code example works:

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);


            })();

        }

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

However, this second variation does not work:

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仍然指向我要由于JavaScript闭合而要更改的SPAN.那么,有人可以解释为什么这失败了吗?谢谢.

has no effect on the value of the SPAN I intended. I expected dataNode.bullet to still point to the SPAN I want to change because of JavaScript closure. So, can someone explain why this fails? Thanks.

推荐答案

尝试一下:

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);
}

闭包定义了一个新的范围.这是必需的,因为直到循环结束后才调用您的处理程序,因此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.

这篇关于jQuery事件处理程序的JavaScript关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆