简体   繁体   English

如何在javascript解析中获取选项的值

[英]How to get the value of an option in javascript parsing

Good day am having an HTML code in which i intend to get the innerText of a selected option美好的一天,我有一个 HTML 代码,我打算在其中获取所选选项的 innerText

<div class="bag-option">
<div class="bag-option-label">colour:</div>
<div class="bag-option-control">
    <select name='select-colour-0' id='select-colour-0' onchange="onColourSelected(this, '0', '1', 'style-img-thb-', '_WLG.jpg', '_WXL.jpg', '_SKC.jpg');displayUpdateMsg();return false;">
        <option value="0" selected>orchid pink</option>
    </select>
</div>

You can get using:您可以使用:

document.getElementById("select-colour-0").getElementsByTagName("option")[document.getElementById("select-colour-0").selectedIndex].innerHTML

What exactly the code does is:代码的作用是:

  1. Select the <select> tag.选择<select>标签。
  2. Get find all the <option> tags.获取所有<option>标签。
  3. Get the selectedIndex of the <select> .获取<select>selectedIndex
  4. Get the particular <option> tag with the selectedIndex .使用selectedIndex获取特定的<option>标签。
  5. Get the innerHTML of the <option> which is always a text.获取始终是文本的<option>innerHTML

A working demo of the code is below...代码的工作演示如下...

Snippet片段

 <select name='select-colour-0' id='select-colour-0' onchange="onColourSelected(this, '0', '1', 'style-img-thb-', '_WLG.jpg', '_WXL.jpg', '_SKC.jpg');displayUpdateMsg();return false;"> <option value="0" selected>orchid pink</option> </select> <script> alert(document.getElementById("select-colour-0").getElementsByTagName("option")[document.getElementById("select-colour-0").selectedIndex].innerHTML); </script>

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

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