首页 > 解决方案 > forEach 在比较选项值和返回父 id 时返回 undefined

问题描述

所以我想抓取所有<select>元素并抓取“国家”下拉菜单的 ID。

我有以下内容,将其推<selects>入 HTMLcollection 然后比较第一个选项,通常是“阿富汗”。如果为 true,则返回 parentName.id 的值

这就是理论,但我一直不确定。任何见解将不胜感激?

const selectsAvailable = document.getElementsByTagName("select"),
            countryList = Object.keys(selectsAvailable).forEach((collectedSelect, i) => {
    selectsAvailable[collectedSelect].options[0].value === 'Afghanistan' && selectsAvailable[collectedSelect].options[0].parentNode.id;
});

console.log("countryList>>>>>>", countryList);

标签: javascriptshort-circuitinghtmlcollection

解决方案


语法似乎有点不对劲。.map()如果满足条件,using将返回某些内容,但.map()在 a 上不起作用,nodelist因此您需要将其转换为array.

.filter()非常适合这样的事情,但它返回 HTML 元素而不是 ID,所以我们将坚持使用.map().

此外,您正在循环遍历<select>元素,因此您不需要遍历父元素。最后,为了避免不匹配的<select>元素出现空数组项——这是.filter()很好的地方——我将 ID 推送到数组而不是在变量中声明函数:

const selectsAvailable = [...document.getElementsByTagName("select")];
let countryList = [];
selectsAvailable.map(item => {
    return item.options[0].value === 'Afghanistan' ? countryList.push(item.id) : ''
});

console.log("countryList>>>>>>", countryList);
<select id="countries">
  <option value="Afghanistan">Afghanistan</option>
  <option value="Africa">Africa</option>
</select>

<select id="somethingElse">
  <option value="Something">Something</option>
  <option value="Something">Something</option>
</select>


推荐阅读