zl程序教程

您现在的位置是:首页 >  后端

当前栏目

jQuerycontains过滤器实现精确匹配使用方法

方法 实现 使用 匹配 精确 过滤器
2023-06-13 09:14:49 时间

复制代码代码如下:


<!DOCTYPEhtml>
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title></title>
<!--<scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"type="text/javascript"></script>-->
<scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"type="text/javascript"></script>
<scripttype="text/javascript">
$(function(){
//根据select中的option的文本来执行选中
//$("#selectboxoption[text="第二项"]");
//$("#selectboxoption").filter("[text="第二项"]");
//上面两种写法都是错误的
//正确写法
$("#btn4").click(function(){
var$option=$("#selectboxoption:contains("第二项")").map(function(){
if($(this).text()=="第二项"){
returnthis;
}
});
alert($option.length>0?"有对象":"无对象");
$option.attr("selected",true);
});
});
</script>
</head>
<body>
<formid="form1">
<div>
<selectid="selectbox">
<optionvalue="1">第一项</option>
<optionvalue="2">第二项</option>
<optionvalue="21">第二项1</option>
</select>
<inputtype="button"id="btn4"value="contains测试"/>
</div>
</form>
</body>
</html>

$(".selector:contains("xx")")
  contains()只作匹配查找,不够精确,包含xx的selector和包含xxabc的selector都会查到。

解决办法:
?$(".selector:contains("xx")[innerHTML="xx"]")
  这样将查找内容只有xx的selector。