javascript 使用javascript按值获取选择选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26832539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get select option by value using javascript
提问by Simon
I have selection menu:
我有选择菜单:
<div class="selector">
<select>
<option value="valueA">Value A</option>
<option value="valueB">Value B</option>
<option value="valueC">Value C</option>
</select>
</div>
and I need Javascript (no jquery!) to get option by value and change it's text (innerHtml)
我需要Javascript(没有jquery!)来按值获取选项并更改它的文本(innerHtml)
for example when I run the function I need to get option with the value "valueB" from class "selector" and change it's text to Value Whatever.
例如,当我运行该函数时,我需要从“选择器”类中获取值为“valueB”的选项,并将其文本更改为“值不管”。
回答by David says reinstate Monica
I'd suggest:
我建议:
document.querySelector('div.selector option[value=valueB]').text = 'Value whatever';
Further, in answer to the questions raised in comments:
此外,在回答评论中提出的问题时:
I need to get only the second
<option>
element with the same value as the other<option>
and change text only to the second<option>
我只需要获取与另一个
<option>
具有相同值的第二个元素,<option>
并将文本更改为第二个<option>
To get all <option>
elements with value="valueB"
:
获取所有<option>
元素value="valueB"
:
document.querySelectorAll('div.selector option[value=valueB]')[1].text = 'Value whatever';
The differences are that document.querySelector()
returns only the first (if any) match to the supplied CSS selector, as a node (rather than a NodeList
), so properties are available directly; document.querySelectorAll()
returns allthe elements, in a NodeList
, that match the supplied selector; so we have to use the (zero-based) index ([1]
) to retrieve a specific node, and get/set its properties.
不同之处在于document.querySelector()
只返回第一个(如果有)匹配到提供的 CSS 选择器,作为一个节点(而不是一个NodeList
),所以属性是直接可用的;document.querySelectorAll()
返回a中与提供的选择器匹配的所有元素NodeList
;所以我们必须使用(从零开始的)索引 ( [1]
) 来检索特定节点,并获取/设置其属性。
回答by free4ride
document.querySelector('[value=valueB]').innerHtml="innerHtml"
for text document.querySelector('[value=valueB]').text="text"
用于文本 document.querySelector('[value=valueB]').text="text"