如何使用普通js返回nodelist的索引

How to return the index of a nodelist using vanilla js?

本文关键字:nodelist 索引 返回 js 何使用      更新时间:2023-09-26

我有一些东西,我想从jquery转换到js。

我使用js创建12 li元素,当点击得到索引号,在jquery中我使用。index()函数来实现这一点,

var month = $(".calenderApp__calender__allMonths__month"),
    startMonth;
$(month).on('click', function () {
    startMonth = $(this).index() + 1;
});

我该怎么做呢?在普通js中,我已经讲到

var month = document.querySelectorAll(".calenderApp__calender__allMonths__month"),
    startMonth;
for (var i=0; i<month.length; i++) {       
    month[i].addEventListener("click", function () {
        startMonth = this; //returns full html element, just need index number
    });
}

将索引存储在元素中。

var month = document.querySelectorAll(".calenderApp__calender__allMonths__month"),
    startMonth;
for (var i=0; i<month.length; i++) {
    month[i].index = i;
	
    month[i].addEventListener("click", function () {
        alert(this.index+1);
    });
}
<ul>
  <li class="calenderApp__calender__allMonths__month">Jan</li>
  <li class="calenderApp__calender__allMonths__month">Feb</li>
  <li class="calenderApp__calender__allMonths__month">March</li>
  <li class="calenderApp__calender__allMonths__month">Apr</li>
</ul>

这是传统的闭包在循环中的问题。实际上,这个用例是ajax流行之前人们询问的原始用例。因此,您可以使用传统的解决方案:

for (var i=0; i<month.length; i++) {
    (function(j){
        month[i].addEventListener("click", function () {
            startMonth = j; // j is the captured value of i
        });
    })(i); // capture value of `i` here to break closure
}

至于为什么会发生这种情况,请阅读以下内容:请解释JavaScript闭包在循环中的使用,或者在SO或其他地方关于闭包在循环中的任何一页。