在代码中,触发了点击事件,但array[i]
被打印null
。
如果我单击任何索引,则会打印" "
。为什么打印null
而不是点击值?
请建议解决方案...它甚至不打印array[last index]
...它只是打印null or " "
这是我的代码:
function abc() {
var array = ["1","2","3","4","5","6","7","8","9","0"];
var innerHTML = "";
for (var i = 0; i < 10; i++) {
innerHTML += "<div id = \"MyID_"+i+" \"></div>" ;
}
var xyz = document.getElementById("OuterHTML");
xyz.innerHTML = innerHTML;
for (var i = 0; i < 10; i++) {
var tempID = "#MyID_"+i;
$(tempID).on("tap", function(album){
console.log(array[i]);
})
}
}
答案 0 :(得分:1)
使用闭包,你可以这样做
for (var i = 0; i < 10; i++) {
var tempID = "#MyID_"+i;
(function(x){
$(tempID).on("click", function(album){
console.log(array[x]);
});
}(i));
}
使用事件委托
$('#OuterHTML').on('click', function (e) {
console.log(array[$(e.target).index()]);
});
检查此fiddle