[英]Attaching Event Handlers to JQuery-generated DOM Elements
I'm pulling some data from an external API and then displaying it in a dashboard page. 我正在从外部API中提取一些数据,然后将其显示在仪表板页面中。 To do this, I'm generating DOM elements once I've processed the data, like so:
为此,一旦处理完数据,便会生成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>");
}
However, when I click on any of the newly generated span
elements, I get an alert with the last value in companies
. 但是,当我单击任何一个新生成的
span
元素时,都会收到有关companies
的最后一个值的警报。 For example, if I had declared: 例如,如果我声明了:
var companies = {
"Google": 3,
"Apple": 4
};
then clicking on both the Google span
and the Apple span
would alert 4
. 然后同时单击Google
span
和Apple span
将发出警报4
。 My desired behavior is clicking on the Google span
to alert 3
. 我想要的行为是单击Google
span
以发出警报3
。
How about this:- 这个怎么样:-
Attach the event handler using event delagtion with on()
just once. 使用事件延迟与
on()
附加一次事件处理程序。 (See the class added compName
). (请参阅在类中添加
compName
)。 and just using its id
. 并仅使用其
id
。
See Delegated event handler reference here . 请参阅此处的委托事件处理程序参考。 If somediv already exist in DOM then you can just use
$('#someDiv').on('click','.compName',function(){...
如果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"));
}
//...
})
You need to capture the key
value with a closure, since the loop will have finished by the time the click
handler actually executes. 您需要使用闭包捕获
key
,因为循环将在click
处理程序实际执行时完成。 Try this: 尝试这个:
.click((function() {
return function () {
alert(key);
};
})());
Or, you can just alert
its id
, since that's what you set it as: 或者,您只需
alert
其id
,因为这是您将其设置为的内容:
.click(function () {
alert(this.id);
});
That's because the variable key gets changed before you call the function. 这是因为在调用函数之前,变量键已更改。 You need a closure around it to prevent it from modified by the outer code:
您需要在其周围进行封闭,以防止外部代码对其进行修改:
for(var key in companies) {
$(document.createElement("span"))
.attr({ id: key })
.appendTo($("#someDiv"))
.click((function(privatekey) {
return function(){
alert(privatekey);
};
})(key));
$("#"+key).html("<b>" + key + "</b>: $"+companies[key]+"<br>");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.