【问题标题】:Get text of the selected option with jQuery [duplicate]使用 jQuery 获取所选选项的文本 [重复]
【发布时间】:2011-09-21 04:38:09
【问题描述】:

我有一个带有一些值的选择框。如何获取选定的选项文本,而不是值?

<select name="options[2]" id="select_2">
    <option value="">-- Please Select --</option>
    <option value="6" price="0">100</option>
    <option value="7" price="0">125</option>
    <option value="8" price="0">150</option>
    <option value="9" price="0">175</option>
    <option value="10" price="0">200</option>
    <option value="3" price="0">25</option>
    <option value="4" price="0">50</option>
    <option value="5" price="0">75</option>
</select>

我试过了:

$j(document).ready(function(){
    $j("select#select_2").change(function(){
        val = $j("select#select_2:selected").text();
        alert(val);
    });
});

但它会以undefined 回来。

【问题讨论】:

    标签: javascript jquery html drop-down-menu jquery-selectors


    【解决方案1】:

    关闭,可以使用

    $('#select_2 option:selected').html()
    

    【讨论】:

    • $('#select_2 :selected').html() 也可以吗?
    • @JoseFaeti 显然,是的:jsfiddle.net/jomanlk/kcWQw/7
    • 请记住 $('#select_2').find('option:selected').html() 会更有效;)。
    • @Archangel 很公平,这只是您的原始评论听起来对这个例子来说会更有效,如果它是可以忽略不计的,因为它们基本上做同样的事情。使用.find() 可能是有益的(就像我今天早些时候遇到的情况一样),但根据我的经验,它更像是一种间接的方法,因为我很少需要使用它,因为通常有更好的方法。
    • @Damian 我同意你的看法。实际上,我应该指定它“通常”会更有效,但并非总是如此。
    【解决方案2】:
    $(document).ready(function() {
        $('select#select_2').change(function() {
            var selectedText = $(this).find('option:selected').text();
            alert(selectedText);
        });
    });
    

    Fiddle

    【讨论】:

    • 这是最优雅的...尤其是当您将选择作为对象时
    • 当您将选择分配给变量时,例如foo = $('#select2) 这是要使用的变体,如foo.find('option:selected').text()
    【解决方案3】:

    将选择器更改为

    val = j$("#select_2 option:selected").text();
    

    您选择的是&lt;select&gt; 而不是&lt;option&gt;

    【讨论】:

      【解决方案4】:

      这个也可以考虑

      $('#select_2').find('option:selected').text();
      

      虽然我不确定,但这可能是一个更快的解决方案。

      【讨论】:

        【解决方案5】:

        您实际上可以将 value = 放到文本中,然后执行

        $j(document).ready(function(){
            $j("select#select_2").change(function(){
                val = $j("#select_2 option:selected").html();
                alert(val);
            });
        });
        

        或者我在类似案例中所做的是

        <select name="options[2]" id="select_2" onChange="JavascriptMethod()">
          with you're options here
        </select>
        

        使用第二个选项,您应该有一个未定义的。 如果有效,请给我反馈:)

        帕特里克

        【讨论】:

          猜你喜欢
          • 2015-03-04
          • 1970-01-01
          • 2015-08-20
          • 1970-01-01
          • 2014-12-01
          • 2012-11-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多