Home >Web Front-end >JS Tutorial >Detailed explanation of how jQuery uses the contains filter to achieve exact matching_jquery
The example in this article describes how jQuery uses the contains filter to achieve exact matching. Share it with everyone for your reference, the details are as follows:
The:contains selector selects elements that contain the specified string.
The string can be text contained directly within the element, or contained within a child element.
is often used together with other elements/selectors to select elements containing specified text in a specified group, such as:
$("p:contains(is)") means to select all e388a4556c0f65e1904146cc1a846bee elements that contain "is".
Another example:
$("p:contains(张三)") or $("p:contains("张三")") means selecting all e388a4556c0f65e1904146cc1a846bee elements that contain "张三".
You can also use variables in this selector to achieve the purpose of selection, such as:
$(document).ready(function(){ var ddd="John"; $("div:contains(‘" + ddd + "‘)").css("color", "#f00"); });
We can also use jquery's filter method and contains method together to achieve more fuzzy matching, such as:
$(document).ready(function(){ $(".box").filter(":contains(李)").css("color", "#f00"); });
means to set the text color of the box containing "李" to red.
jQuery uses the contains filter to achieve exact matching:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <!--<script src="jquery.min.js" type="text/javascript"></script>--> <script src="jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { //根据select中的option的文本来执行选中 //$("#selectbox option[text='第二项']"); //$("#selectbox option").filter("[text='第二项']"); //上面两种写法都是错误的 //正确写法 $("#btn4").click(function () { var $option =$("#selectbox option:contains('第二项')").map(function(){ if ($(this).text() == "第二项") { return this; } }); alert($option.length > 0 ? "有对象" : "无对象"); $option.attr("selected", true); }); }); </script> </head> <body> <form id="form1"> <div> <select id="selectbox"> <option value="1">第一项</option> <option value="2">第二项</option> <option value="21">第二项1</option> </select> <input type="button" id="btn4" value="contains测试" /> </div> </form> </body> </html>
Readers who are interested in more jQuery-related content can check out the special topics on this site: "JQuery drag effects and skills summary", "jQuery extension skills summary", "JQuery common classic special effects summary", "jQuery animation and special effects usage summary" and "jquery selector usage summary"
I hope this article will be helpful to everyone in jQuery programming.