<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>demo</title> </head> <body> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> </body> <script> var lis = document.getElementsByTagName(‘li‘); for (var i = 0; i < lis.length; i++) { (function(i){ lis[i].addEventListener(‘click‘,function(e){ console.log("li",lis[i].innerText); },false); })(i) } </script> </html>
目的:保证索引值不被污染,因为变量i是全局变量。
时间: 2024-10-17 06:23:19