HTMLSelectElement: selectedOptions 属性
只读的 HTMLSelectElement 属性 selectedOptions 包含一个列表,其中列出了当前被选中的 <option> 元素。这个已选项列表是一个 HTMLCollection 对象,其中每个当前选中的选项都有一个条目。
如果选项具有 HTMLOptionElement.selected 属性,则认为该选项被选中。
值
一个 HTMLCollection,列出了所有当前被选中的 HTMLOptionElement,它们或者是 HTMLSelectElement 的子元素,或者是 <select> 元素内 HTMLOptGroupElement 的子元素。
换句话说,<select> 元素内的任何选项都可能包含在结果中,但选项组(option groups)不包含在此列表中。
如果没有选项被选中,则该集合为空,其 length 为 0。
示例
在此示例中,使用一个包含多个选项的 <select> 元素,让用户订购各种食品。
HTML
创建选择框和代表每种食品选择的 <option> 元素的 HTML 如下所示:
html
<label for="foods">What do you want to eat?</label><br />
<select id="foods" name="foods" size="7" multiple>
<option value="1">Burrito</option>
<option value="2">Cheeseburger</option>
<option value="3">Double Bacon Burger Supreme</option>
<option value="4">Pepperoni Pizza</option>
<option value="5">Taco</option>
</select>
<br />
<button name="order" id="order">Order Now</button>
<p id="output"></p>
<select> 元素被设置为允许选择多个项目,并且它有 7 行高。还请注意 <button>,它的作用是触发使用 selected 属性来获取已选元素集合。
JavaScript
设置按钮事件处理程序以及事件处理程序本身的 JavaScript 代码如下所示:
js
let orderButton = document.getElementById("order");
let itemList = document.getElementById("foods");
let outputBox = document.getElementById("output");
orderButton.addEventListener("click", () => {
let collection = itemList.selectedOptions;
let output = "";
for (let i = 0; i < collection.length; i++) {
if (output === "") {
output = "Your order for the following items has been placed: ";
}
output += collection[i].label;
if (i === collection.length - 2 && collection.length < 3) {
output += " and ";
} else if (i < collection.length - 2) {
output += ", ";
} else if (i === collection.length - 2) {
output += ", and ";
}
}
if (output === "") {
output = "You didn't order anything!";
}
outputBox.textContent = output;
});
此脚本在“立即订购”按钮上设置了一个 click 事件监听器。当被点击时,事件处理程序会使用 selectedOptions 获取已选项的列表,然后遍历列表中的选项。将构建一个字符串来列出订购的物品,并使用正确的英语语法规则(包括 牛津逗号)来构建列表。
结果
最终显示的内容如下:
规范
| 规范 |
|---|
| HTML # dom-select-selectedoptions-dev |
浏览器兼容性
加载中…