jquery-traversing:选择 – >选项 – >文本

我想比较一个变量和一个选择 – >选项 – >选择的文本,以便更改“选定”的attrib,这是我的代码,它可以工作,但我认为这不是写它的最佳方式,请原谅我的英语,我用google翻译求助hehehehe:

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

这是html:

  example 1 example 2  

这是一些尝试

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

您可以尝试以下方法,而不是遍历每个:

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

要么

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

同样也适用。 这取决于您的变量lista是完全匹配还是仅需要部分匹配。

你拥有的东西没有任何问题,jQuery会在引擎盖下做同样的事情。

如果要将它们全部链接在一起,可以使用filter()

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

:contains可能适合你,但它就像一个通配符匹配,例如cat会匹配类别

 var lista = 'example 1'; $('#id option:contains(' + lista + ')')[0].selected = true; 

你的方式非常有效,但可以更像这样:

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

这使用原生属性,因此速度更快。

  • .text属性提供元素的文本内容

  • .selected设置所选属性

  • return false; 一旦被选中,它将打破循环,因此它不会不必要地继续

这应该工作:

 $("#id option").attr('selected', function() { return this.innerHTML === lista; }); 

我可能已经太晚了。

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

这比那时快了约97%

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

检查性能日志, url为http://jsperf.com/selector-performance-00000