如何通过将文本与纯 Javascript 匹配来获取选择菜单中选项的索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7489982/
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
How to get the index of an option in a select menu by matching the text with plain Javascript?
提问by Zoolander
I have a select menu and I need to dynamically select the option based on the text value of the option element. For example, my select looks like this:
我有一个选择菜单,我需要根据选项元素的文本值动态选择选项。例如,我的选择如下所示:
<select id="names">
<option value="">Please Select</option>
<option value="1">John</option>
<option value="2">Steve</option>
<option value="3">Max</option>
</select>
If I have the string "Max", how can I get that the index of the option is 4 so I can dynamically set this as the selectedIndex with JavaScript?
如果我有字符串“Max”,我怎么能得到选项的索引是 4,这样我就可以用 JavaScript 动态地将它设置为 selectedIndex?
No jQuery.
没有 jQuery。
采纳答案by Incognito
You want to select the element, iterate over the array, find the text value, and return the index.
您要选择元素、遍历数组、找到文本值并返回索引。
- Don't use InnerHTML, it's slow and breaks and not standards compliant
- Dont use innerText, simmilar reasons but not quite as serious
- Do use a function so you can do it all over again.
- Do select the child text node, and retreives the nodeValue, which is cross-browser friendly
- 不要使用 InnerHTML,它很慢,而且不符合标准
- 不要使用innerText,原因类似但没那么严重
- 一定要使用一个函数,这样你就可以重新做一遍。
- 选择子文本节点,并检索nodeValue,这是跨浏览器友好的
Example:
例子:
function indexMatchingText(ele, text) {
for (var i=0; i<ele.length;i++) {
if (ele[i].childNodes[0].nodeValue === text){
return i;
}
}
return undefined;
}
回答by ipr101
Try this, it should find and then select the relevant option in the select box.
试试这个,它应该找到然后在选择框中选择相关选项。
var searchtext = "max";
for (var i = 0; i < listbox.options.length; ++i) {
if (listbox.options[i].text === searchtext) listbox.options[i].selected = true;
}
回答by karim79
回答by Einacio
in PLAIN js
在普通js中
var sel, opts, opt, x, txt;
txt='Max';
sel=document.getElementById('names');
opts=sel.options;
for (x=0;x<opts.lenght;x++){
if (opts[x].text === txt){
opt=opts[x];
}
}
回答by Brian Colvin
var x = document.getElementById("names");
for(var i = 0; i<x.options.length; i++){
if("Max" == x.options[i].text){
doSomething();
//maybe x.selectedIndex = i;
}
}
回答by topek
This should do the trick:
这应该可以解决问题:
var options = document.getElementsByTagName('select')[0].children,
i,
l = options.length,
index;
for(i = 0; i < l; i++){
if(options[i].firstChild.nodeValue === 'Max'){index = i};
}
Please note that the index is zero based, what mean it is one less than you would expect.
请注意,该指数是从零开始的,这意味着它比您预期的要小 1。
回答by jimbo
[edit - expanded to include non-jquery method]
[编辑 - 扩展到包括非 jquery 方法]
I strongly recommendusing jQuery for this since the solution is a one-liner:
我强烈建议为此使用 jQuery,因为解决方案是单行的:
jQuery('#names option:contains("Max")').val()
However, here's a pure JavaScript implementation anyway:
然而,这里有一个纯 JavaScript 实现:
function findOption( select, matchMe ) {
var
// list of child options
options = select.getElementsByTagName('option'),
// iteration vars
i = options.length,
text,
option;
while (i--) {
option = options[i];
text = option.textContent || option.innerText || '';
// (optional) add additional processing to text, such as trimming whitespace
text = text.replace(/^\s+|\s+$/g);
if (text === matchMe) {
return option.getAttribute('value');
}
}
return null;
}
Example usage:
用法示例:
alert(
findOption(
document.getElementsByTagName('select')[0],
"Max"
)
);
Alerts 3
警报 3
回答by Dennis
The options property stores the options in a select menu - iterate over it and compare the contents.
options 属性将选项存储在选择菜单中 - 对其进行迭代并比较内容。
var list = document.getElementById("names").options;
for(var i = 0; i<list.length; i++){
if(list[i].text== "Max") { //Compare
list[i].selected = true; //Select the option.
}
}
JSFiddle: http://jsfiddle.net/cuTxu/2
JSFiddle:http: //jsfiddle.net/cuTxu/2