javascript - 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);
解决方案
语法似乎有点不对劲。.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>
推荐阅读
- laravel - Laravel Postgres SQLSTATE [42601]:语法错误:7 错误:“”“”处或附近的零长度分隔标识符
- c++ - 即使所有数组都被删除 C++,内存仍然泄漏
- python - 为什么我的决策树 ML 算法训练越来越完美?
- erlang - 警告:未定义的回调函数终止/3(行为'gen_statem')**
- python - 使用软标签训练 xgboost
- ffmpeg - FFmpeg:为什么 avcodec_receive_frame 需要额外的数据包来获取 I 帧
- python - 对 Pandas 数据透视表应用过滤器会清除数据
- javascript - 数据格式几乎完成,但不显示烛台图
- python - 在 O(lg n) 中查找 Python 列表的唯一数字对中的单个数字
- java - 我可以覆盖在 Java 中返回 Unit 类型的 kotlin 方法吗