如何通过JavaScript获取下拉菜单选中项的索引值?
解决点击月份选项获取对应索引的问题
不用硬编码月份名称,有两种简单的方式在点击时直接获取选中项的索引:
方法一:利用forEach的索引参数
在forEach循环遍历元素时,第二个参数就是当前元素在集合中的索引,直接在点击事件里使用这个索引即可:
const monthText = document.querySelector(".month-text"); const months = document.querySelectorAll(".month-value"); const monthsEl = Array.from(months); months.forEach((el, index) => { el.onclick = function () { const monthSelected = this.innerHTML; monthText.textContent = monthSelected; console.log('选中月份文本:', monthSelected); console.log('对应索引:', index); }; });
方法二:通过元素本身在数组中的位置获取索引
如果需要基于monthsEl数组来获取索引,可以直接用indexOf(this),因为点击事件里的this就是当前被点击的元素:
const monthText = document.querySelector(".month-text"); const months = document.querySelectorAll(".month-value"); const monthsEl = Array.from(months); monthsEl.forEach(el => { el.onclick = function () { const monthSelected = this.innerHTML; monthText.textContent = monthSelected; const index = monthsEl.indexOf(this); console.log('选中月份文本:', monthSelected); console.log('对应索引:', index); }; });
这两种方法都能避免硬编码的问题,其中方法二更可靠——如果存在文本相同的选项,用元素本身匹配索引不会出错,而基于文本的indexOf可能拿到错误的索引。
内容的提问来源于stack exchange,提问作者guaPeo USA
相关产品推荐
相关产品推荐

