简体   繁体   English

在JavaScript中将选择器用于下拉列表

[英]Using selectors for droplists in JavaScript

如果我知道下拉列表的ID,我就可以使用javascript来使用下拉菜单来选择一个下拉列表,但是如果该下拉列表没有ID,则无法选择它,所以我想知道是否可以选择页面上所有未使用ID的下拉列表?

document.getElementById("id").selectedIndex = 0;

To select all 全部选择

const all = document.querySelectorAll('select');

To select the first 选择第一个

const first = document.querySelector('select');
console.log(first.selectedIndex);

edit: 编辑:

Here you can see an example how too loop the multiple select-boxes and set the selectedIndex (in my case to 3) 在这里,您可以看到一个示例,如何循环多个选择框并设置selectedIndex(在我的情况下为3)

 const all = document.querySelectorAll('select'); [...all].forEach(select => select.selectedIndex = 3); 
 <select> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option> </select> <select> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> 

all is a NodeList and with [...all] or optional Array.from(all) you get an Array. all是一个NodeList,使用[...all]或可选的Array.from(all)您将获得一个Array。 This is needed to use the Array-Method forEach 这是使用Array- forEach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM