jquery-traversing:select - >选项 - >文本 [英] jquery-traversing: select -> option -> text
本文介绍了jquery-traversing:select - >选项 - >文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想比较一个变量和一个select - >选项 - >选择的文本以便更改selectedattrib,这是我的代码,它可以工作,但我认为这不是写它的最好方法,请原谅我英语,我用google翻译求助hehehehe:
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');
}
});
这里是html:
<select id="id" >
<option value="0" >example 1</option>
<option value="1" >example 2</option>
</select>
这里有几次尝试
$('#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
是否需要完全匹配或只是部分匹配。
Works just as well. It just depends if your variable lista
will need to be an exact match or just a partial one.
这篇关于jquery-traversing:select - >选项 - >文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文