问: i 会输出什么?改写成闭包的写法?
<a href="javaScript:void(0)">a</a> <a href="javaScript:void(0)">b</a> <a href="javaScript:void(0)">c</a> <script type='text/javascript'> var arr = document.getElementsByTagName('a'); for(var i=0;i<arr.length;i++) { arr[i].onclick = function() { console.log(this + '我是第'+ i +'几个'); } } </script>
答:全部输出都是”我是第3个“
闭包写法可解决问题
<a href="javaScript:void(0)">a</a> <a href="javaScript:void(0)">b</a> <a href="javaScript:void(0)">c</a> <script type='text/javascript'> var arr = document.getElementsByTagName('a'); for(var i=0;i<arr.length;i++) { (function(i,v){ v.onclick = function() { console.log(this + '我是第'+ i +'个'); } })(i,arr[i]) } </script>