[英]Can't attach the event listeners to the dynamically created buttons
我需要在文檔中添加一些按鈕,並使它們調用getTest()
函數。 因此,一個按鈕應調用getTest(1)
,第二個按鈕應調用getTest(1)
getTest(2)
,依此類推。 但是,一旦腳本完成,事件偵聽器將僅附加到循環中的最后一個按鈕。
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;
}
}
我該如何處理? 如何將事件偵聽器附加到我創建的每個按鈕上?
這是因為附加的循環是同步的,結束並且在發生單擊時cur_i的值始終是迭代器的最后一個值。 您需要將其包裝到本地范圍內。
(function(cur_i){
bu.addEventListener("click", function() {
getTest(cur_i);
});
}(cur_i));
這樣可以確保在綁定時該值正確。
您實際上應該改用document.createElement
並將事件直接附加到元素上,而不是通過DOM傳遞,這會比較慢。
同樣, innerHTML
是不可變的,每執行一次+=
,都會重新創建全部內容,因此在每次迭代中,您都將破壞舊的/先前的元素並重新添加它們,但沒有它們的事件處理程序!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.