返回for循环中的单击按钮

时间:2015-07-27 10:30:30

标签: javascript loops for-loop javascript-events

如何返回值' 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);
        }
    }
}

1 个答案:

答案 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);
}