document.body.innerHTML = "<div id='div1'><button>111</button></div>" + "<div id='div2'><button>222</button></div>" + "<div id='div3'>333</div>" + "<div id='div4'>444</div>"; for (var i = 0; i < 4; i++) { document.getElementById('div' + i).addEventListener('click', function () { alert(i);//4 }); } document.body.innerHTML = "<div id='div1'><button>111</button></div>" + "<div id='div2'><button>222</button></div>" + "<div id='div3'><button>333</button></div>" + "<div id='div4'><button>444</button></div>"; for (var i = 0; i < 4; i++) { !function (i) { document.getElementById('div' + i).addEventListener('click', function () { alert(i);//1,2,3 }); } (i); }什么鬼呀,click 什么啊?,能把完整源代码提供一下吗?
"click"双引号
document.body.innerHTML="<div id='div1'>aaa</div><div id='div2'>bbb</div><div id='div3'>ccc</div>"; //给页面添加三个div元素 for(var i=1;i<4;i++){ !function(i){ document.getElementById('div'+i).addEventListener("click",function(){ //对象.addEventListener("事件名",闭包引用外面作用域的函数(这里为i)) alert(i);//点击每个div弹出的i均不一样 }) }(i);//形成闭包,把每个i单独传入(立即执行函数) }
addEventListener DOM2级操作方法,可以同时绑定多个事件,在这里为每个div绑定了click事件,可以去搜下addEventListener
document.body.innerHTML = "<div id='div1'><button>111</button></div>" + "<div id='div2'><button>222</button></div>" + "<div id='div3'>333</div>" + "<div id='div4'>444</div>"; for (var i = 0; i < 4; i++) { document.getElementById('div' + i).addEventListener('click', function () { alert(i);//4 }); }
document.body.innerHTML = "<div id='div1'><button>111</button></div>" + "<div id='div2'><button>222</button></div>" + "<div id='div3'><button>333</button></div>" + "<div id='div4'><button>444</button></div>"; for (var i = 0; i < 4; i++) { !function (i) { document.getElementById('div' + i).addEventListener('click', function () { alert(i);//1,2,3 }); } (i); }