小编Ric*_*ley的帖子

如何使用 JavaScript 在点击事件中获取数组元素的索引

我正在开发一个电子应用程序,对于代码的这个特定部分,我有必要恢复当前元素的索引(点击)。

HTML:

<div>
    <input type="checkbox" class="optionBox"> Minimize to tray after 10 seconds
    <input type="checkbox" class="optionBox"> Always check day transition
</div>
Run Code Online (Sandbox Code Playgroud)

JavaScript:

modifierCheckboxes = document.querySelectorAll('.optionBox');

for (var i = 0; i < modifierCheckboxes.length; i++) {
    modifierCheckboxes[i].addEventListener('click', function (e) {
        bindModifierCheckBoxes(e);
    });
}

function bindModifierCheckBoxes(e) {
    // I need the reference for modifierCheckboxes[i] here 
}
Run Code Online (Sandbox Code Playgroud)

我试过这个:

function bindModifierCheckBoxes(e){
    var t=e.target;
    console.log(Array.prototype.indexOf.call(t.parentNode.childNodes,t));
}
Run Code Online (Sandbox Code Playgroud)

它“接近”了,但是当我单击第一个复选框时,我的索引为 1,而在第二个复选框中,我得到了 3。

请不要使用外部库,只需简单的 JavaScript。

html javascript dom

1
推荐指数
1
解决办法
1万
查看次数

标签 统计

dom ×1

html ×1

javascript ×1