后期绑定onclick事件 [英] Late binding onclick event

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

问题描述

按照我的javscript的一部分(使用jquery)。

Following part of my javscript(using jquery).

list = ['a', 'b', 'c'];
for(var i = 0 ; i< list.length ; i++) {
   $("<a>click here</a>").
      click(function(){
          foo(list[i]);
      }).
      appendTo('#sometag');
}
function foo(val) {
    console.log(val);
}

始终打印c,无论您单击哪个标记。如何打印正确的值?

看起来它使用了i = 3的最后一个值,因此总是评价oc

always prints c, no matter which tag you click on. How do I print proper value ???
It seems that it is using the last value of i=3 and thus evaluating o c always

推荐答案

在触发事件处理程序之前,迭代完成后,您需要一个 closure 新范围,因此当点击发生时,循环结束, i 是它设置的最后一个值,新范围保持 i 本地到该范围的值

You'll need a closure new scope as the iteration finishes before the event handler is triggered, so when the click happens, the loop has finished and i is the last value it's set to, a new scope keeps the value of i local to that scope

list = ['a', 'b', 'c'];

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

   (function(j) {

       $("<a>click here</a>").click(function(){
          foo(list[j]);
       }).appendTo('#sometag');

   }(i));

}

function foo(val) {
    console.log(val);
}

另一个选择是添加更多jQuery

Another option is to add more jQuery

list = ['a', 'b', 'c'];

$.each(list, function(index, item) {
    $("<a />", {text : 'click here',
                on   : {
                    click : function() {
                        foo(item);
                    }
                }
    }).appendTo('#sometag');
});

function foo(val) {
    console.log(val);
}

这篇关于后期绑定onclick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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