jquery如何根据text选择option
2018-01-05 16:13
225 查看
度出来的代码都是这样的:
[javascript] view
plain copy
$('#test option[text="b"]').attr("selected",true);
或
[javascript] view
plain copy
$('#test').find('option[text="b"]').attr("selected",true);
然而,在我的代码中却不起作用,不知原因为何!
终于在海量无用的搜索结果中找到一条线索,解决了问题:
原因:上面两种方法在jquery低于1.4.2的版本(含)中有效,在更高版本中无效!
解决一:精确匹配,选择文本与所给字符串完全一样的option。
[javascript] view
plain copy
$('#test option').filter(function(){return $(this).text()=="b";}).attr("selected",true);
解决二:子串匹配,选择文本包含所给字符串的option。
[javascript] view
plain copy
$("#test option:contains('b')").attr('selected', true);
解决三:自定义函数(网上找的,在此感谢作者)
[javascript] view
plain copy
$("#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;
}
}
});
[javascript] view
plain copy
$('#test option[text="b"]').attr("selected",true);
或
[javascript] view
plain copy
$('#test').find('option[text="b"]').attr("selected",true);
然而,在我的代码中却不起作用,不知原因为何!
终于在海量无用的搜索结果中找到一条线索,解决了问题:
原因:上面两种方法在jquery低于1.4.2的版本(含)中有效,在更高版本中无效!
解决一:精确匹配,选择文本与所给字符串完全一样的option。
[javascript] view
plain copy
$('#test option').filter(function(){return $(this).text()=="b";}).attr("selected",true);
解决二:子串匹配,选择文本包含所给字符串的option。
[javascript] view
plain copy
$("#test option:contains('b')").attr('selected', true);
解决三:自定义函数(网上找的,在此感谢作者)
[javascript] view
plain copy
$("#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
- jquery如何根据text选择option
- jquery如何书写一个根据下拉选择列表的选择值 控制其他标签时候显示的功能
- jquery根据option的text定位选中option
- jquery 获取下拉框 某个text='xxx'的option的属性 非选中 如何获得select被选中option的value和text和......
- 如何根据select选择的值反查option的属性
- jquery获取select中已经选择的option中的text文本
- Oracle如何根据SQL_TEXT生成SQL_ID
- jQuery获取Select选择的Text和 Value(转)
- jquery获取select中的option的text值
- asp.net SqlParameter如何根据条件有选择的添加参数
- JQuery 获取多个select标签option的text内容(实例)
- jQuery获取Select option 选择的Text和 Value(转)
- jQuery获取Select option 选择的Text和Value
- 【jQuery】:text表单文本选择器
- jQuery获取Select选择的Text和 Value
- jQuery获取Select选择的Text和 Value(转)
- jQuery获取Select选择的Text和Value:
- jQuery获取Select选择的Text和 Value