繁体   English   中英

寻找哪个<Option>被选中<select>(没有 JQuery)

[英]Finding which <Option> is selected in <select> (without JQuery)

我有以下元素:

<select id="color" name="colorId" class="btn secondary">
    <option value="347366" selected="selected">Purple</option>
    <option value="56634">White</option>
</select>

我想找到选择了哪个选项:

下面只给我默认值:

document.querySelector('#color option[selected="selected"]')

(我知道如何使用 JQuery 但我不能使用 jQuery 或任何其他类似的库)

使用 :checked 选择器。 这适用于复选框、单选和选择

document.querySelector('#color option:checked')

对于节点

document.querySelector('#color option:checked').value

对于价值

在普通的javascript中:

var select = document.getElementById('color');
var currentOpt = select.options[select.selectedIndex]; 

JsBin 示例: http ://jsbin.com/ogunet/1/edit(打开你的 js 控制台)

这将返回选定的选项值和文本。希望这对你有用..

干杯

var elt = document.getElementById('color');

 // get option selected
    var option = elt.options[elt.selectedIndex].value;
    var optionText = elt.options[elt.selectedIndex].text;

使用getElementById()获取<select> DOM元素并获取其参数selectedIndex

var select = document.getElementById( 'color' ),
    selIndex = select.selectedIndex;,
    selElement = select.getElementsByTagName( 'option' )[ selIndex ];

您可以使用querySelectorAll而不是querySelector

document.querySelectorAll('option:checked')[0].innerText

要么

document.querySelectorAll('option:checked')[0].value

selectedOptions在希望从 select 元素中取回所选选项时是一个有效选项

文档中的演示:

 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>

暂无
暂无

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

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