我从外部 API 中提取一些数据,然后将其显示在仪表板页面中。为此,我在处理数据后生成 DOM 元素,如下所示:
for(var key in companies) {
$(document.createElement("span"))
.attr({ id: key })
.appendTo($("#someDiv"))
.click(function() {
alert(key);
});
$("#"+key).html("<b>" + key + "</b>: $"+companies[key]+"<br>");
}
但是,当我单击任何新生成的 span
元素时,我会收到一条警告,其中包含 companies
中的最后一个值。例如,如果我声明:
var companies = {
"Google": 3,
"Apple": 4
};
然后单击 Google span
和 Apple span
将发出警报 4
。我想要的行为是点击 Google span
来提醒 3
。
最佳答案
这个怎么样:-
仅使用一次 on()
使用事件延迟来附加事件处理程序。 (请参阅添加的类 compName
)。并仅使用其id
。
请参阅委派事件处理程序引用 here 。如果 DOM 中已经存在 somediv 那么你可以使用 $('#someDiv').on('click','.compName',function(){...
$(function(){
$(document).on('click','.compName',function(){
//.....
alert(this.id);
//....
});
....
for(var key in companies) {
$(document.createElement("span"))
.attr({ id: key, 'class':'compName' }).html("<b>" + key + "</b>: $"+companies[key]+"
<br>").html("<b>" + key + "</b>: $"+companies[key]+"<br>").
.appendTo($("#someDiv"));
}
//...
})
关于javascript - 将事件处理程序附加到 JQuery 生成的 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16500496/