百度出来的代码都是这样的:
- $('#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;
- }
- }
- });
参考网址:
http://stackoverflow.com/questions/3744289/jquery-how-to-select-an-option-by-its-text