jquery-traversing: select -> option -> text

2019-06-19 07:27发布

I want to compare a variable with a select -> option -> text selected in order to change the "selected" attrib, here is my code, it works but I think is not the best way to write it, excuse my English, I used google translate for help hehehehe :

var lista = 'example 1'; 
$("#id option").each(function(){
  if($(this).text() == lista){
    $(this).attr('selected','selected');
  }
});

here's the html:

<select id="id" >
  <option value="0" >example 1</option>
  <option value="1" >example 2</option>
</select>

here's a few attempts

$('#id option:eq("'+lista+'")').attr('selected','selected')

$("#id option[text='"+lista+"']").attr('selected','selected')

5条回答
Fickle 薄情
2楼-- · 2019-06-19 08:11

Your way is pretty efficient, but could be made a little more so like this:

var lista = 'example 1'; 
$("#id option").each(function(){
    if( this.text == lista ){
      this.selected = true;
      return false;
    }
});

This uses native properties so it will be faster.

  • .text property gives the text content of the <option> element

  • .selected sets the selected property

  • return false; will break the loop once one is selected, so it doesn't needlessly continue

查看更多
何必那么认真
3楼-- · 2019-06-19 08:14

Instead of looping through each, you can try this:

var lista = 'example 1'; 
$('#id option:contains(' + lista + ')').attr('selected', true);

or

$('#id option:[text="' + lista + '"]').attr('selected', true);

Works just as well. It just depends if your variable lista will need to be an exact match or just a partial one.

查看更多
时光不老,我们不散
4楼-- · 2019-06-19 08:15

There's nothing wrong with what you have, jQuery will be doing more-or-less the same under the hood.

You could use filter() if you want to chain it all together:

var lista = 'example 1'; 
$('#id option').filter(function () { 
    return $(this).text() == lista; 
})[0].selected = true;

:contains might work for you but it works like a wildcard match, e.g. cat would match category:

var lista = 'example 1'; 
$('#id option:contains(' + lista + ')')[0].selected = true;
查看更多
一夜七次
5楼-- · 2019-06-19 08:17

I'm probably too late.

var lista = 'example 1';
$('#id option[text="' + lista + '"]').attr('selected', true);

This is about 97% faster then

var lista = 'example 1';
$('#id option:contains("' + lista + '")').attr('selected', true);

check performance log at http://jsperf.com/selector-performance-00000

查看更多
别忘想泡老子
6楼-- · 2019-06-19 08:33

This should work:

$("#id option").attr('selected', function() {
    return this.innerHTML === lista;
});
查看更多
登录 后发表回答