Javascript 通过文本值从下拉列表中选择一个选项元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5638513/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:11:34  来源:igfitidea点击:

Selecting an option element from a dropdown by its text value

javascriptdrop-down-menu

提问by Wooble

Given an HTML form element like:

给定一个 HTML 表单元素,例如:

<select id='mydropdown'>
  <option value='foo'>Spam</option>
  <option value='bar'>Eggs</option>
</select>

I know I can select the first option with

我知道我可以选择第一个选项

document.getElementById("mydropdown").value='foo'

However, say I have a variable with the value "Spam"; can I select a dropdown item by its text rather than by its value?

但是,假设我有一个值为“Spam”的变量;我可以通过文本而不是值来选择下拉项吗?

回答by David Waters

var desiredValue = "eggs"
var el = document.getElementById("mydropdown");
for(var i=0; i<el.options.length; i++) {
  if ( el.options[i].text == desiredValue ) {
    el.selectedIndex = i;
    break;
  }
}

回答by daniellmb

I'd use the selectedIndex or a loop to select the option by text, the code below doesn't work.

我会使用 selectedIndex 或循环来按文本选择选项,下面的代码不起作用。

document.getElementById("mydropdown").text = 'Eggs';

回答by Vismari

If you want to get an option by its innertext and not by the value you can do this:

如果您想通过其内部文本而不是通过值获得选项,您可以这样做:

function go(){
    var dropdown = document.getElementById('mydropdown');
    var textSelected = 'Spam';

    for(var i=0, max=dropdown.children.length; i<max; i++) {
        if(textSelected == dropdown.children[i].innerHTML){
            alert(textSelected);
            return;
        }
    }
}

回答by kennebec

Older IE does not handle options of a select as child nodes, but all browsers implement the textproperty of a select's option collection.

较旧的 IE 不会将 select 的选项作为子节点处理,但所有浏览器都实现了 select 选项集合的text属性。

function selectbytext(sel, txt){
    if(typeof sel== 'string'){
        sel= document.getELementById(sel) || document.getELementsByName(sel)[0];
    }
    var opts= sel.options;
    for(var i= 0, L= opts.length; i<L; i++){
        if(opts[i].text== txt){
            sel.selectedIndex= i;
            break;
        }
    }
    return i;
}