它與變量的作用域有關。addEventListener將添加一個事件,此時雖然會觸發回調,但循環已完成執行&buttonText將用最新值更新。這導致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 = functio