如何为addEventListener的回调函数的参数添加forEach索引?

时间:2017-03-05 13:48:09

标签: javascript foreach

我有一个forEach循环,为每个复选框添加一个事件监听器。我想添加到回调中调用的函数,我们在循环中的索引如下:

function handleCheck(e, counter){

    console.log(counter); //This should print the counter
    console.log(e); //this should print the event
    console.log(this); //this should print the checkbox

}

checkboxes.forEach(function(checkbox, counter){
    checkbox.addEventListener('click', handleCheck(counter));
});

但参数没有正确传递..你能告诉我我误解的是什么吗?

2 个答案:

答案 0 :(得分:1)

尝试以下方法:



#[1300000 rows x 2 columns]
df = pd.concat([df]*100000).reset_index(drop=True)   
#print (df)

In [53]: %timeit (df.loc[df.TICKET.duplicated(keep=False), 'Client'].value_counts())
10 loops, best of 3: 54.8 ms per loop

In [54]: %timeit (df.groupby('TICKET').filter(lambda x: len(x) > 1)['Client'].value_counts())
1 loop, best of 3: 282 ms per loop

function handleCheck(e, counter, thisObj){

    console.log(counter); //This should print the counter
    console.log(e); //this should print the event
    console.log(thisObj); //this should print the checkbox

}
var chkboxes = document.getElementsByTagName('input');
var checkboxesArray = [];
for(var i=0; i<chkboxes.length; i++){
	checkboxesArray[i] = chkboxes[i].outerHTML;
}
checkboxesArray.forEach(function(checkbox, index) {
    chkboxes[index].addEventListener('click', function (index) {
        return function (e) {
            handleCheck(e.type, index, this);
        }
    }(index));
});
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以使用counter上的闭包并返回一个调用handleCheck的函数。

checkboxes.forEach(function(checkbox, counter) {
    checkbox.addEventListener('click', function (counter) {
        return function (e) {
            handleCheck(e, counter);
        }
    }(counter));
});