//闭包实现.
for (var i = 0; i < 5; i++) {
var btn = document.createElement('button');
btn.appendChild(document.createTextNode('按钮' + i));
btn.addEventListener('click', (function(i) {
return function() { alert(i); };
})(i));
document.body.appendChild(btn);
}
//两种方式
for (var i = 0; i < 5; i++) {
var btn = document.createElement('button');
btn.appendChild(document.createTextNode('按钮' + i));
(function(x){
btn.addEventListener('click', function() {
alert(x);
})
})(i)
document.body.appendChild(btn);
}
console