如何使用 vanilla js return 节点列表的索引?
How to return the index of a nodelist using vanilla js?
我有一些东西想从 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
}
至于为什么会发生这种情况,请阅读以下内容:Please explain the use of JavaScript closures in loops 或关于 SO 或其他地方的循环闭包的数十页中的任何一页。
我有一些东西想从 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
}
至于为什么会发生这种情况,请阅读以下内容:Please explain the use of JavaScript closures in loops 或关于 SO 或其他地方的循环闭包的数十页中的任何一页。