如何返回值' i'什么时候点击它而不担心其他人?
var button = UTILS.getElementsByClassName('btn primary');
for(var i = 0; i<button.length; i++){
if(button[i].attachEvent){
button[i].attachEvent('onclick',function(){/*...*/});
}else{
button[i].addEventListener('click',function(){/*...*/},false);
}
}
}
答案 0 :(得分:0)
您可以绑定值
var button = UTILS.getElementsByClassName('btn primary');
for(var i = 0; i<button.length; i++){
if(button[i].attachEvent){
button[i].attachEvent('onclick',buttonEvent.bind(button[i], i));
}else{
button[i].addEventListener('click',buttonEvent.bind(button[i], i),false);
}
}
function buttonEvent(i){
// this refers to the button, i is the number used in the for loop
console.log(this, i);
}