开始写的类似于这种:
- $('#test option[text="b"]').attr("selected",true);
- $('#test').find('option[text="b"]').attr("selected",true);
然而,代码却不生效,不知原因为何! 最终解决了问题:
原因:上面两种方法在jquery低于1.4.2的版本(含)中有效,在更高版本中无效!
解决一:精确匹配,选择文本与所给字符串完全一样的option。
- $('#test option').filter(function(){return $(this).text()=="b";}).attr("selected",true);
解决二:子串匹配,选择文本包含所给字符串的option。
- $("#test option:contains('b')").attr('selected', true);
解决三:自定义函数
$("#btn").click(function(){
var count=$("#sel").get(0).options.length;
for(var i=0;i<count;i++){
if($("#sel").get(0).options[i].text == "b")
{
$("#sel").get(0).options[i].selected = true;
break;
}
}
});
转载自:
jquery如何根据text选择option