<button>按钮0</button> <button>按钮1</button> <button>按钮2</button> <button>按钮3</button> <button>按钮4</button> <button>按钮5</button> <button>按钮6</button> <button></Button 7button> <button>按钮8</button> <button>按钮9</button>
@ Demand: click the button corresponding to the button to print subscript var btns = document.querySelectorAll ( 'Button' ) // Method a: do not use closures for ( var I = 0; I <btns.length; I ++ ) { btns [I] .index = I; btns [I] .onclick = function () { // the console.log (I); the console.log ( the this .index); } } // characteristics of closures: embedded inside a function sets another function, local variables inside a function reference external function, thus forming a closure @ two: closures var btns = document.querySelectorAll ( 'Button' ) for ( var i=0;i<btns.length;i++) { (function(index){ btns[index].onclick=function(){ console.log(index); } })(i); } // 方法三:使用了闭包 var btns = document.querySelectorAll('button') for (var i = 0; i < btns.length; i++) { btns[i].onclick = (function(index){ return function () { console.log(index); } })(i); }