使用立即调用函数表达式(IIFE)或let关键字来解决。例如:
for (var i = 0; i < elements.length; i++) { (function(index) { elements[index].addEventListener("click", function() { console.log("clicked element " + index); }); })(i); }
for (let i = 0; i < elements.length; i++) { elements[i].addEventListener("click", function() { console.log("clicked element " + i); }); }