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

标签 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));
});

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

最佳答案

尝试以下操作:

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/

相关文章:

c# - 排序列表项(最新的优先)

javascript - 如何从 String.prototype.replace() 方法中的回调返回正确的值?

javascript - 动态添加和删除项目以选择jquery

javascript - 正则表达式

javascript - 如何找到json文件中最小的数字

c# - 如何使 JQuery 屏蔽输入插件在 asp.net Ajax 更新面板中的 AsyncPostback 之后工作?

vb.net - 对于每个循环迭代计数

Javascript 附加新的 onClick 项目格式错误

c# - 退出循环时 foreach 中的集合突变 : is it an acceptable pattern?

javascript - MVC foreach循环唯一id C#