问问题
23032 次
6 回答
23
使用 :checked 选择器。这适用于复选框、单选和选择
document.querySelector('#color option:checked')
对于节点
document.querySelector('#color option:checked').value
为价值
于 2014-06-05T19:36:06.517 回答
10
在纯 JavaScript 中:
var select = document.getElementById('color');
var currentOpt = select.options[select.selectedIndex];
JsBin 示例: http: //jsbin.com/ogunet/1/edit(打开你的 js 控制台)
于 2013-01-15T08:36:15.913 回答
1
这将返回选定的选项值和文本。希望这对你有用..
干杯
var elt = document.getElementById('color');
// get option selected
var option = elt.options[elt.selectedIndex].value;
var optionText = elt.options[elt.selectedIndex].text;
于 2013-01-15T08:40:10.687 回答
0
使用获取<select>
DOM元素getElementById()
并获取其参数selectedIndex
:
var select = document.getElementById( 'color' ),
selIndex = select.selectedIndex;,
selElement = select.getElementsByTagName( 'option' )[ selIndex ];
于 2013-01-15T08:37:43.073 回答
0
你可以这样querySelectorAll
做querySelector
document.querySelectorAll('option:checked')[0].innerText
或者
document.querySelectorAll('option:checked')[0].value
于 2019-11-30T22:04:51.297 回答
0
selectedOptions在从选择元素中取回所选选项时是一个有效选项
文档中的演示:
let orderButton = document.getElementById("order");
let itemList = document.getElementById("foods");
let outputBox = document.getElementById("output");
orderButton.addEventListener("click", function() {
let collection = itemList.selectedOptions; // <-- used here
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.innerHTML = output;
}, false);
<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>
于 2021-07-02T06:46:15.473 回答