简体   繁体   中英

dynamically add EventListener doesn't work as expected

When I try to dynamically fill a wrapper element with HTML elements, and then add an EventListener for that element, it only uses the last value.

 window.onload=function(){ sW=""; for(var i = 0; i < 5; i++) { var e = document.createElement('div'); e.innerHTML = "test div number "+i; e.addEventListener('click', function() {alert("t:"+i);}); document.getElementById('wrap').appendChild(e); } } 
 <html> <body> <div id="wrap"></div> </body> </html> 

That's because var keeps the the reference to the variable. Use let instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM