【问题标题】:How to know the value of an <option> with certain content in JavaScript?如何知道 JavaScript 中具有特定内容的 <option> 的值?
【发布时间】:2013-04-17 17:16:38
【问题描述】:

我做了很多搜索,但我无法解决我的问题。

<select id="my_select">
    <option value="Findme_1">Knowing_1
    <option value="Findme_2">Knowing_2
</select>

在一个函数中,我需要找到内容中带有“Findme_1”的选项的值。

请问我该怎么做?

编辑:我不需要找到所选选项的值,我也不需要使用它的索引找到选项的值,我只知道内容“Knowing_1”,我想知道值“ Findme_1"。

我想过一个循环,但可能还有其他更常见的方式?

【问题讨论】:

  • 请在发布问题之前检查答案。SO Click中已经有一个帖子
  • 如果你会使用 jQuery,那么看看this
  • 是的,很抱歉没有说,但我可以使用 jQuery。你的回答似乎很好,我会在我的脚本上检查这个,谢谢。
  • 编辑了我的答案以反映其他人的正确解决方案

标签: javascript select option


【解决方案1】:

使用这个。 example

   $('#my_select').find('option[text="Knowing_1"]').val()

【讨论】:

    【解决方案2】:

    使用 SelectedIndex 属性。 Check This

    【讨论】:

    • 我对 Selected 选项不感兴趣,我正在处理选项的“内容”。
    • 如何获取内容?
    【解决方案3】:

    这将提醒所选选项的值:

    (function() {
    
        var select = document.getElementById('my_select');
        select.addEventListener('change', function(){
            alert( select.options[select.selectedIndex].value );
        });
    
    })();
    

    另外,你应该关闭你的选项元素:

    <select id="my_select">
        <option value="Test_1">Findme_1</option>
        <option value="Test_2">Findme_2</option>
    </select>
    

    完整代码和预览:http://jsfiddle.net/CX5aq/

    【讨论】:

      【解决方案4】:

      首先,您的 html 不正确,您缺少关闭标记。应该是这样的

      <select id="my_select">
          <option value="Test_1">Findme_1 </option>
          <option value="Test_2">Findme_2 </option>
      </select>
      

      然后我猜,每当用户选择下拉菜单时,您都希望通过 javascript 获取值,所以现在编写一个 javascript

      <script> 
          document.getElementById('my_select').onchange = function(){
      
            var my_value = this.value; // you have your new value on the variable my_value
      
          }; 
      </script> 
      

      【讨论】:

        【解决方案5】:

        要通过文本查找&lt;option&gt;,您可以遍历options collection 并检查textContent(标准)或innerText(IE,非标准):

        function valueByText(select, text) {
            var options = select.options;
            var textContent;
        
            for (var i = 0, l = options.length; i < l; i++) {
                textContent = options[i].textContent || options[i].innerText;
        
                if (textContent.indexOf(text) >= -1) {
                    return options[i].value;
                }
            }
        
            return null;
        }
        
        var result = valueByText(document.getElementById('my_select'), 'Knowing_1');
        

        示例:http://jsfiddle.net/jXpS2/


        此外,如果您有可用的 DOM 库,它们可以帮助简化此操作。

        如jQuery的:contains() selector:

        var result = $('#my_select option:contains("Knowing_1")').val();
        

        示例:http://jsfiddle.net/rcjfj/

        【讨论】:

          猜你喜欢
          • 2022-01-11
          • 2021-09-21
          • 1970-01-01
          • 2021-09-19
          • 2022-07-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多