[英]Can't attach the event listeners to the dynamically created buttons
I need to add some buttons in my document and make them call getTest()
function. 我需要在文档中添加一些按钮,并使它们调用
getTest()
函数。 So 1 button should call getTest(1)
, the 2nd one - getTest(2)
and so on. 因此,一个按钮应调用
getTest(1)
,第二个按钮应调用getTest(1)
getTest(2)
,依此类推。 But once the script was completed, the event listener is only attached to the last button in the loop. 但是,一旦脚本完成,事件侦听器将仅附加到循环中的最后一个按钮。
window.onload = function() {
var button_place = document.getElementById("buttons_here"); // get an element
/* add the event listeners */
var i = 0;
while(i < 10) {
var cur_i = i + 1;
var current_but_name = "but_" + (i + 1);
button_place.innerHTML += "<button class=button id='" + current_but_name + "'>" + cur_i + "</button>\n";
var bu = document.getElementById(current_but_name);
//bu.style.color = "#F00";
bu.addEventListener("click", function() {
getTest(cur_i);
});
++i;
}
}
How can I deal with it? 我该如何处理? How can I attach an event listener to the every button I created?
如何将事件侦听器附加到我创建的每个按钮上?
this is because the loop that attaches is syncronous, finishes and the value of cur_i is always the last value of the iterator when the click occurs. 这是因为附加的循环是同步的,结束并且在发生单击时cur_i的值始终是迭代器的最后一个值。 you need to wrap this into a local scope.
您需要将其包装到本地范围内。
(function(cur_i){
bu.addEventListener("click", function() {
getTest(cur_i);
});
}(cur_i));
this will ensure that the value is correct as of the time of binding. 这样可以确保在绑定时该值正确。
you really should use document.createElement
instead and attach the events directly to the element rather than passing through the DOM, which is slower. 您实际上应该改用
document.createElement
并将事件直接附加到元素上,而不是通过DOM传递,这会比较慢。
also, innerHTML
is immutable and every +=
you do, recreates the whole lot so on each iteration, you are destroying the old/previous elements and re-adding them but without their event handlers! 同样,
innerHTML
是不可变的,每执行一次+=
,都会重新创建全部内容,因此在每次迭代中,您都将破坏旧的/先前的元素并重新添加它们,但没有它们的事件处理程序!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.