繁体   English   中英

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

[英]How to get index of an array element in click event with JavaScript

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

HTML:

<div>
    <input type="checkbox" class="optionBox"> Minimize to tray after 10 seconds
    <input type="checkbox" class="optionBox"> Always check day transition
</div>

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 
}

我试过这个:

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

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

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

也许您可以将对象选择器转换为数组,然后您可以使用 indexOf。

var checks = document.querySelectorAll('.optionBox');

checks.forEach(function(check){
  check.addEventListener('click', checkIndex);
})

function checkIndex(event){
  console.log( Array.from(checks).indexOf(event.target) );
}

利用闭包

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

modifierCheckboxes.forEach(function(checkbox, i) {
    checkbox.checked = customConf[i];;
    checkbox.addEventListener('click', function (e) {
        bindModifierCheckBoxes(e, i);
    });
});

function bindModifierCheckBoxes(e, index) {
    // index is passed inside the event listener function
}

使用.children而不是.childNodes ... .children给出了不包括文本节点的子元素列表

在 HTML 中,当您很好地格式化源代码时, ><之间的文本节点(通常)不会影响页面的呈现

function bindModifierCheckBoxes(e) {
    var t=e.target;
    var checkboxes = t.parentNode.getElementsByClassName('optionBox');
    console.log(Array.prototype.indexOf.call(checkboxes, t) + 1);
}

这是一个小提琴: https : //jsfiddle.net/7p3gsy75/

另一种选择是给您的复选框 ID(这里我选择了蹩脚的):

<div>
  <input type="checkbox" id="cb1" class="optionBox"> Minimize to tray after 10 seconds
  <input type="checkbox" id="cb2" class="optionBox"> Always check day transition
</div>

然后查看e.target.id

您可以使用change而不是click

 $('.optionBox').on('change', function() { $(this).each(function() { if (this.checked) { alert($(this).index()); } else { alert("unchecked"); } }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <input type="checkbox" class="optionBox"> Minimize to tray after 10 seconds <input type="checkbox" class="optionBox"> Always check day transition </div>

将 modifierCheckboxed[i] 传递给您的 bindModifierCheckBoxes 函数。 所以你发送当前复选框的 référence 然后你可以用它做你想做的事。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM