【问题标题】:How to get the index value from a dropdown menu?如何从下拉菜单中获取索引值?
【发布时间】:2022-11-02 00:10:20
【问题描述】:

仅限 JavaScript! 从下拉菜单中单击一个元素后,我试图获取索引。 我已经得到了文本值,但没有得到索引。我该如何解决这个问题?

1)这是我点击一个月后获取文本值的方式:

const monthText = document.querySelector(".month-text");
const months = document.querySelectorAll(".month-value");
const monthsEl = Array.from(months);

months.forEach((el) =\> {
el.onclick = function () {
const monthSelected = (monthText.textContent = this.innerHTML);
console.log(monthSelected);
};
});

2)我正在获取索引,但使用硬代码(“May”):

const monthsArr = monthsEl.map((el) => el.textContent);
console.log(monthsArr);
const index = monthsArr.indexOf("May");
console.log(index);

【问题讨论】:

标签: javascript


【解决方案1】:

map 的第二个参数是数组中正在处理的当前元素的索引。也许你可以检查一下。与每个相同。

地图((元素,索引)=> { /* ... */ })

Array.prototype.map()

Array.prototype.forEach()

【讨论】:

    【解决方案2】:

    在您的 map 函数中,传递第二个参数并将其命名为 index,它将返回对象在数组中的位置。

    const monthsArr = monthsEl.map((el, index) => el.textContent = el.index);
    

    Learn more about Index in mapping

    【讨论】:

      最近更新 更多