Javascript javascript更改选择选项文本

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

javascript change select option text

javascripthtml

提问by meWantToLearn

Im trying to modify the text of the first select option via javascript. But it empties the entire select option

我试图通过 javascript 修改第一个选择选项的文本。但它清空了整个选择选项

 <select name='stuff'>
      <option value="a"> Pepsi </option>
      <option value= "b"> Juice </option>
 </select>


<script type="text/javascript">
    document.getElementsByName('stuff')[0].innerHTML = "Water";
</script>

回答by CodingIntrigue

You want to read from the optionscollection and modify the first element in there:

您想从options集合中读取并修改其中的第一个元素:

document.getElementsByName('stuff')[0].options[0].innerHTML = "Water";

回答by Satya Ranjan Sahoo

You can try this:

你可以试试这个:

 $('select[name=stuff] option:first').html("abcd");

回答by Florin Pop

I think this should work:

我认为这应该有效:

 <select name='stuff'>
          <option id="first" value="a"> Pepsi </option>
          <option value= "b"> Juice </option>
     </select>


    <script type="text/javascript">
        document.getElementById("first").innerHTML = "Water";
    </script>