传递迭代变量以单击循环内部的事件
Pass iteration variable to click events inside for loop
我有以下代码:
var i = 0;
for (var anchor in window.globals.html.anchors) {
var value = window.globals.html.anchors[anchor];
value.addEventListener('click', function(i) {
var currData = window.globals.data[i],
data_clientId = 0;
if (currData.client_product_id !== undefined) {
data_clientId = currData.getAttribute('data_clientId');
} else if (currData.product_id !== undefined) {
data_clientId = currData.product_id;
}
Statistics.send(data_clientId);
window.open(window.globals.data[i].url, '_blank');
}(i));
i++;
}
这意味着我想通过点击事件监听器内的interator访问全局数组。如果我不向点击事件传递i
,我将在每次迭代中获得可能的最大数量,因为i
将是一个全局变量。
但在这里,点击事件的所有迭代似乎都是在点击任何东西之前调用的,即onload。
为什么会这样,怎么了?
看起来您正在调用处理程序,同时试图将其添加到addEventListener
中。您需要将其封装在一个函数中,从而创建一个封装i
变量的闭包。
var i = 0;
for (var anchor in window.globals.html.anchors) {
var value = window.globals.html.anchors[anchor];
value.addEventListener('click', (function(i) {
return function() {
var currData = window.globals.data[i],
data_clientId = 0;
if (currData.client_product_id !== undefined) {
data_clientId = currData.getAttribute('data_clientId');
} else if (currData.product_id !== undefined) {
data_clientId = currData.product_id;
}
Statistics.send(data_clientId);
window.open(window.globals.data[i].url, '_blank');
}
}(i)));
i++;
}
现在请注意,传递给addEventListener
的函数会立即被调用,并返回一个函数本身,其中变量i
的作用域是该函数。
相关文章:
- 对于循环-在循环内部循环,用于获取带有ascii值的字母表
- 可能只在for循环内部运行一次代码块
- 循环内部的递归函数未按预期工作
- 在处理元素单击事件期间,在循环内部调用window.open()
- 将Timout设置为循环内部
- Confusing For循环内部有超时和关闭
- 循环内部的Javascript异步调用
- if数组元素在for循环内部有条件
- for循环内部If语句的JavaScript正确语法
- while循环内部的函数
- 让ajax在服务器端的for循环内部或外部更好?Javascript
- 循环内部的函数-如何正确执行
- 最好在循环内部还是外部声明临时变量
- Parse.com 循环内部查询
- 循环内部的延迟不起作用
- GM_xmlhttpRequest WHILE 循环内部
- 如何在for循环内部使用AJAX
- 循环内部的jQuery mouseover()函数赋值不正确
- Javascript,setInterval在while循环之后开始?如何使它在while循环内部启动
- SyntaxError:缺少;在for循环内部时的before语句