它与变量的作用域有关。
addEventListener
将添加一个事件,此时虽然会触发回调,但循环已完成其执行&
buttonText
将用最新值更新。这是造成
按钮文本
item3
. 一种选择是更换
for (var buttonText of ["item1", "item2", "item3"]) {
for (let buttonText of ["item1", "item2", "item3"]) {
window.onload = function() {
for (let buttonText of ["item1", "item2", "item3"]) {
let button = document.createElement("button");
button.textContent = buttonText;
button.addEventListener("click", function() {
console.log(`${buttonText} was clicked!`);
});
document.getElementById("body").append(button);
}
}
<div id='body'></div>
另一个选择是可以创建
closure
IIFE
window.onload = function() {
for (var buttonText of ["item1", "item2", "item3"]) {
(function(txt) {
var button = document.createElement("button");
button.textContent = txt;
button.addEventListener("click", function() {
console.log(`${txt} was clicked!`);
});
document.getElementById("body").append(button);
}(buttonText))
}
}
<div id='body'></div>