【问题标题】:Jquery Javascript HTML selectsJquery Javascript HTML 选择
【发布时间】:2012-02-08 16:15:21
【问题描述】:

所以我有一个标准的选择下拉菜单。选择中的一个选项(最后一个)我有一个文本字符串 - var abc。

<select id="exampleselect">
     <option>123</option>
     <option>xyz</option>
     <option>ABC</option>
</select>

var abc = "ABC";

我要做的是通过选择进行搜索,找到与 var abc 的匹配项,然后将 var abc 的匹配项更改为选定选项。

我尝试过的:

//gets all the options from the select
var selectoptions = $('#exampleselect').find('option').text(); 

//if there is a match of var abc to any of the options in the select
if (selectoptions == abc)
    {
       //work out how to get the index/eq of the matched element

       //put matched element as selected value
       $('#exampleselect').val(matchedelementindex);
    }

【问题讨论】:

  • 那么您希望最后一个选项是动态的吗?值将如何设置?

标签: javascript jquery drop-down-menu


【解决方案1】:

直播example

由于不使用 value 属性,所以可以使用以下代码:

var myVar = 'xyz';

$('#exampleselect option').each(function(e) {
    var $this = $(this);
    if ($this.text() === myVar) {
        $this.prop('selected', true);
        return false; // stops the iteration
    }
});

您也可以使用:contains() 选择器在一行中完成。 但是如果您有一个带有文本“ABC”的选项和另一个带有“ABCD”的选项,这可能不起作用:

$('#exampleselect option:contains('+myVar+')').prop('selected', true);

不过,我建议您为选项元素添加一个 value 属性:

<select id="exampleselect">
     <option value="123">123</option>
     <option value="xyz">xyz</option>
     <option value="ABC">ABC</option>
</select>

这样你就可以做到:

$('#exampleselect').val(myVar);

【讨论】:

  • +1 建议使用value。一个更简洁的解决方案。
【解决方案2】:

试试这个:

var abc = "ABC";
$("#exampleselect option").each(function() {
    if ($(this).text() == abc) {
        $(this).attr("selected", true);
        return false; // exit each loop
    }
})

或者这个,虽然它的可读性稍差:

var abc = "ABC";
$("#exampleselect option").each(function() {
    $(this).attr("selected", $(this).text() == abc);
})

【讨论】:

    【解决方案3】:

    这个小提琴可以帮助你。 您可以通过 jQuery 支持的 CSS 选择器来实现这一点

    var searched="abc";
    $('select option['+searched+']').attr("selected","selected");
    

    http://jsfiddle.net/7EzqU/

    【讨论】:

      【解决方案4】:
      // iterate all select options using jquery .each method    
      $('#exampleselect option').each(function () {
      
          // check if current option text is equal to 'ABC'
          if ($(this).text() == 'ABC') {
      
              // get index of option
              var index = $('#exampleselect').index($(this))
      
              // set selectedIndex property to change to this option
              $('#exampleselect').prop('selectedIndex', index);
          }
      })
      

      【讨论】:

        【解决方案5】:

        这应该可以解决问题: http://jsfiddle.net/xXEVw/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-16
          • 1970-01-01
          • 1970-01-01
          • 2012-07-22
          • 1970-01-01
          相关资源
          最近更新 更多