我正在尝试将一个函数运行到许多元素, 所以我正在使用for循环。我不明白为什么我没有得到任何价值。
var i;
var aFields = ["#business1A","#business1B","#business1C","#business1D","#business2A","#business2B","#business2C","#business2D",
"#business3A","#business3B","#business3C","#business3D","#business4A","#business4B","#business4C","#business4D",
"#business5A","#business5B","#business5C","#business5D","#business6A","#business6B","#business6C","#business6D"];
for (i = 0; i < aFields.length; i++) {
$(aFields[i]).keyup(function(){
alert($(aFields[i]+'Warning') + " - " +$(aFields[i]).val());
});
}
答案 0 :(得分:1)
那是因为你在事件处理程序的回调函数中使用了变量i
。事件在循环结束时发生,因此变量包含的索引超出了数组中的最后一项。
要使用绑定事件的迭代中的变量值,可以使用立即执行的函数表达式创建范围,为每次迭代创建一个变量:
var i;
var aFields = ["#business1A","#business1B","#business1C","#business1D","#business2A","#business2B","#business2C","#business2D",
"#business3A","#business3B","#business3C","#business3D","#business4A","#business4B","#business4C","#business4D",
"#business5A","#business5B","#business5C","#business5D","#business6A","#business6B","#business6C","#business6D"];
for (i = 0; i < aFields.length; i++) {
(function(j){
$(aFields[j]).keyup(function(){
alert($(aFields[j]+'Warning') + " - " +$(aFields[j]).val());
});
})(i);
}
答案 1 :(得分:1)
试试这个:
var i;
var aFields = ["#business1A","#business1B","#business1C","#business1D","#business2A","#business2B","#business2C","#business2D",
"#business3A","#business3B","#business3C","#business3D","#business4A","#business4B","#business4C","#business4D",
"#business5A","#business5B","#business5C","#business5D","#business6A","#business6B","#business6C","#business6D"];
for (i = 0; i < aFields.length; i++) {
(function(j){
$(aFields[j]).keyup(function(){
alert(($(this).attr('id')+'Warning') + " - " +$(this).val());
});
})(i);
}
答案 2 :(得分:0)
这里的问题是wrong usage of the closure variable i
,变量在所有keyup处理程序之间共享,因此当循环结束时i
将具有值aFields.length
所以{{ 1}}将返回undefined。
尝试
aFields[i]
答案 3 :(得分:0)
其他答案很好地解释了闭包的工作原理,但最干净的解决方案是使用this
来引用所选对象:
var i;
var aFields = ["#business1A","#business1B","#business1C","#business1D","#business2A","#business2B","#business2C","#business2D",
"#business3A","#business3B","#business3C","#business3D","#business4A","#business4B","#business4C","#business4D",
"#business5A","#business5B","#business5C","#business5D","#business6A","#business6B","#business6C","#business6D"];
for (i = 0; i < aFields.length; i++) {
$(aFields[i]).keyup(function(){
alert(this.id + ' Warning - ' + this.value);
});
}