闭包题
**********************************************************************************************************************************
题目:
一般错误答案如下:
1 var li = document.getElementsByTagName('li'); 2 for(var i = 0; i < li.length; i++){ 3 li[i].addEventListener('click',function(){ 4 console.log('我是第' + i + '个li'); 5 },false); 6 }
结果运行结果为,点击不同的li都显示是5
正确答案如下:
(用到立即执行函数)
1 <body> 2 <ul> 3 <li>a</li> 4 <li>a</li> 5 <li>a</li> 6 <li>a</li> 7 <li>a</li> 8 </ul> 9 <script type="text/javascript"> 10 var li = document.getElementsByTagName('li'); 11 12 var li = document.getElementsByTagName('li'); 13 for(var i = 0; i < li.length; i++){ 14 (function(j){ 15 li[j].addEventListener('click',function(){ 16 console.log('我是第' + j + '个li'); 17 },false); 18 19 }(i)); 20 } 21 22 </script> 23 </body>