我想要比较一个变量与一个select ->选项-> text selected,以改变"selected“属性,这是我的代码,它可以工作,但我认为这不是最好的写它的方式,对不起我的英语,我使用谷歌翻译的帮助哈哈哈:
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')发布于 2011-02-16 04:37:42
您可以尝试执行以下操作,而不是遍历each:
var lista = 'example 1';
$('#id option:contains(' + lista + ')').attr('selected', true);或
$('#id option:[text="' + lista + '"]').attr('selected', true);效果也很好。这只取决于您的变量lista是需要完全匹配还是只需要部分匹配。
发布于 2011-02-16 04:45:05
你所拥有的一切都没有错,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;发布于 2011-02-16 04:45:07
你的方法是非常有效的,但也可以做得更像这样:
var lista = 'example 1';
$("#id option").each(function(){
if( this.text == lista ){
this.selected = true;
return false;
}
});这使用了本机属性,因此速度会更快。
.text属性给出了element.selected集的文本内容所选的propertyreturn false;一旦被选中就会中断循环,因此它不需要继续<option> https://stackoverflow.com/questions/5009179
复制相似问题