我有一个 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));
});
但是参数没有正确传递..你能告诉我我误解了什么吗?
最佳答案
尝试以下操作:
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));
});
<input type="checkbox" name="chkbox" value="1"/>Check box 1<br/>
<input type="checkbox" name="chkbox" value="2"/>Check box 2<br/>
<input type="checkbox" name="chkbox" value="3"/>Check box 3<br/>
关于javascript - addEventListener 的回调函数的参数如何添加 forEach 索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42609115/