以下是我的 javascript 的一部分(使用 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
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
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)