【问题标题】:Getting the "newest" selected option's text from multiple select list从多个选择列表中获取“最新”选定选项的文本
【发布时间】:2010-07-22 11:47:37
【问题描述】:

我有一个 HTML 选择列表,可以有多个选择:

<select id="mySelect" name="myList" multiple="multiple" size="3">
   <option value="1">First</option>
   <option value="2">Second</option>
   <option value="3">Third</option> `
   <option value="4">Fourth</option> 
   ...
</select>

我想在每次选择它时获取一个选项的文本。我使用 jQuery 来做到这一点:

$('#mySelect').change(function() {
   alert($('#mySelect option:selected').text());
}); 

看起来很简单,但是如果选择列表已经有一些选定的选项 - 它也会返回它们的文本。例如,如果我已经选择了“Second”选项,在选择“Fourth”选项后,警报会给我带来这个 - “SecondFourth”。那么,jQuery 是否有任何简短的方法来仅获取“当前”选定选项的文本,还是我必须使用字符串并过滤新文本?

【问题讨论】:

    标签: jquery select


    【解决方案1】:

    您可以这样做,保留旧值数组并检查哪个新值不存在,如下所示:

    var val;
    $('#mySelect').change(function() {
     var newVal = $(this).val();
     for(var i=0; i<newVal.length; i++) {
         if($.inArray(newVal[i], val) == -1)
           alert($(this).find('option[value="' + newVal[i] + '"]').text());
     }
     val = newVal;
    }); ​
    

    Give it a try here,当您在&lt;select multiple&gt; 上调用.val() 时,它会返回其选定&lt;option&gt; 元素的值的数组。 We're simply storing that, and when the selection changes, looping through the new values, if the new value was in the old value array ($.inArray(val, arr) == -1 if not found) then that's the new value.之后我们只是使用attribute-equals selector 来获取元素并获取它的.text()

    如果value="" 可能包含引号或其他会干扰选择器的特殊字符,请改用.filter(),如下所示:

    $(this).children().filter(function() {
      return this.value == newVal[i];
    }).text());
    

    【讨论】:

      【解决方案2】:

      在选项上设置一个onClick而不是选择:

      $('#mySelect option').click(function() {
          if ($(this).attr('selected')) {
              alert($(this).val());
          }
      });
      

      【讨论】:

        【解决方案3】:
        var val = ''
        $('#mySelect').change(function() {
           newVal = $('#mySelect option:selected').text();
           val += newVal;
           alert(val); # you need this.
           val = newVal;
        });
        

        或者让我们再玩一些

        val = ''; 
        $('#id_timezone')
          .focus(
            function(){
                val = $('#id_timezone option:selected').text();
            })
          .change(
            function(){
                alert(val+$('#id_timezone option:selected').text())
            });
        

        干杯。

        【讨论】:

        • 这会附加每次选择的所有选项(不仅仅是你点击的那个),导致一个非常大/不断增长的字符串:)
        猜你喜欢
        • 1970-01-01
        • 2022-08-18
        • 1970-01-01
        • 2014-10-14
        • 2020-03-21
        • 2016-08-05
        • 2011-12-30
        • 2015-11-03
        相关资源
        最近更新 更多