[英]Too many click handlers being called
I am using the following function to dynamically populate a div with some text and a button using the array messages : 我正在使用以下函数使用数组消息动态填充一些文本和一个按钮的div:
var populateMessages = function(messages){
for (var index in messages){
(function(){
var id = index;
$("#messages").append(messages[index]["title"])
$("#messages").append("<button>Open</button><br/>").click(function(){console.log(message["id"])})
}())
}
};
This code correctly populates the div with the text and the button. 此代码使用文本和按钮正确填充div。 The problem is that if I click on ANY of the buttons, the click handlers for ALL of them fire. 问题是,如果我单击任何一个按钮,则会触发所有按钮的单击处理程序。 So with two buttons, it should log "0" if I click on the first one and "1" if I click on the second. 因此,如果有两个按钮,则单击第一个按钮时应记录为“ 0”,如果单击第二个按钮则应为“ 1”。 Instead, if I click on either, it logs "0 1" 相反,如果我单击其中任何一个,它将记录为“ 0 1”
I'm not super up on Javascript so I don't know what the issue is. 我对Javascript的了解不是很高,所以我不知道问题出在哪里。
The return value of 的返回值
$("#messages").append("<button>Open</button><br/>")
is #messages
, not the button that was added. 是#messages
,而不是添加的按钮。 So each time through the loop you're adding another click handler to #messages
, not the button. 因此,每次循环时,您都要向#messages
添加另一个单击处理程序,而不是按钮。
Try: 尝试:
$.each(messages, function(index, message) {
$("#messages").append(message.title);
$("<button>Open</button>").click(function() {
console.log(message.id);
}).appendTo("#messages");
$("#messages").append("<br/>");
});
$("#messages").append("<button>Open</button><br/>")
Returns #messages
not button
so you are setting the click event to #message
. 返回#messages
not button
因此将click事件设置为#message
。
Try this: 尝试这个:
$("#messages").append("<button>Open</button><br/>").find("button:last").click(/blabla/)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.