[英]Pass custom variable to anonymous jQuery click function
I want to pass current iteration of foreach loop on click event, yet it returns "undefined" - but why? 我想在click事件上传递foreach循环的当前迭代,但它返回“undefined” - 但为什么呢?
for (var i = 0; i < __ARR_selectors.length; i++) {
__ARR_selectors[i].click( function(e, i) {
console.log(i); //returns undefined
}
Try this: 尝试这个:
for (var i = 0; i < __ARR_selectors.length; i++) {
(function (i) {
__ARR_selectors[i].click( function() {
console.log(i); //returns undefined
});
})(i);
}
The problem with your code is the variable i
is updated for each iteration of the loop, so the click event gets bound to the last value that i
had. 你的代码的问题是
i
为循环的每次迭代更新了变量,因此click事件被绑定到i
拥有的最后一个值。
To get round the issue, create an anonymous function which accepts a parameter of i
which gets round javascript closures. 要解决这个问题,请创建一个匿名函数,该函数接受
i
的参数,该参数可以绕过javascript闭包。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.