我需要为使用jQuery动态插入DOM的项添加一个单击处理程序,对象来自一个返回一个对象的服务,所以我基本上有这个(示例对象):
对象:
var items = {
18: {
content: "<div id=\"content18\" > <img src=\"http://www.google.com/images/srpr/logo11w.png\"> </div>"
},
10: {
content: "<div id=\"content10\" > <img src=\"http://www.google.com/images/srpr/logo11w.png\"> </div>"
},
34: {
content: "<div id=\"content34\" > <img src=\"http://www.google.com/images/srpr/logo11w.png\"> </div>"
},
2: {
content: "<div id=\"content2\" > <img src=\"http://www.google.com/images/srpr/logo11w.png\"> </div>"
},
29: {
content: "<div id=\"content29\" > <img src=\"http://www.google.com/images/srpr/logo11w.png\"> </div>"
},
56: {
content: "<div id=\"content56\" > <img src=\"http://www.google.com/images/srpr/logo11w.png\"> </div>"
},
50: {
content: "<div id=\"content50\" > <img src=\"http://www.google.com/images/srpr/logo11w.png\"> </div>"
},
59: {
content: "<div id=\"content59\" > <img src=\"http://www.google.com/images/srpr/logo11w.png\"> </div>"
},
46: {
content: "<div id=\"content46\" > <img src=\"http://www.google.com/images/srpr/logo11w.png\"> </div>"
},
38: {
content: "<div id=\"content38\" > <img src=\"http://www.google.com/images/srpr/logo11w.png\"> </div>"
},
30: {
content: "<div id=\"content30\" > <img src=\"http://www.google.com/images/srpr/logo11w.png\"> </div>"
},
12: {
content: "<div id=\"content12\" > <img src=\"http://www.google.com/images/srpr/logo11w.png\"> </div>"
},
61: {
content: "<div id=\"content61\" > <img src=\"http://www.google.com/images/srpr/logo11w.png\"> </div>"
},
14: {
content: "<div id=\"content14\" > <img src=\"http://www.google.com/images/srpr/logo11w.png\"> </div>"
}
};
然后我将它们添加到DOM中并(尝试)为每个添加的项添加一个点击处理程序:
var rankingItems = $(".rankingitem"), i = 0, element;
for (var index in items) {
$(rankingItems[i]).after(items[index].content);
// crete listeners
element = $("#content"+index).click(function() {
console.log(index);
});
console.log(element);
i++;
}
问题在于,无论我尝试什么,点击处理程序总是获取对象中的最后一项,但不为每个项目分配一个点击处理程序。也许我在这里错过了什么?
添加了一个JS Bin示例:
http://jsbin.com/batadosepara/1/edit
谢谢!
答案 0 :(得分:1)
由于回调的工作原理,您的index
将始终引用列表中的最后一个。将侦听器创建包装在IIFE中以解决这个问题:
(function(i){
element = $("#content"+i).click(function() {
console.log(adIndex));
});
})(index);
看看这个小提琴,了解它是如何工作的: http://jsfiddle.net/7o7bhkey/
答案 1 :(得分:1)
试试这个,on()函数适用于新附加的DOM元素
var rankingItems = $(".rankingitem"), i = 0, element;
for (var index in items) {
$(rankingItems[i]).after(items[index].content);
});
console.log(element);
i++;
$("div[id^='content']").on("click",function(){
console.log($(this).text());
})
答案 2 :(得分:0)
尝试:
$('body').on('click', 'div[id~="content"]', function(){})