jquery 包含
jQuery 包含方法
jQuery 提供了多种方法来检查元素是否包含特定内容,包括文本、子元素或其他属性。以下是几种常用的方法:
检查元素是否包含特定文本
使用 :contains() 选择器或 text() 方法结合 JavaScript 的 includes() 方法:

// 使用 :contains() 选择器
$("p:contains('特定文本')").css("color", "red");
// 使用 text() 和 includes()
$("p").each(function() {
if ($(this).text().includes("特定文本")) {
$(this).css("color", "red");
}
});
检查元素是否包含特定子元素
使用 has() 方法或 find() 方法:

// 使用 has() 方法
$("div").has("p").css("border", "1px solid red");
// 使用 find() 方法
$("div").each(function() {
if ($(this).find("p").length > 0) {
$(this).css("border", "1px solid red");
}
});
检查元素是否包含特定属性
使用 attr() 方法或 is() 方法:
// 检查元素是否有特定属性
$("a").each(function() {
if ($(this).attr("href")) {
$(this).css("color", "blue");
}
});
// 使用 is() 方法
$("a").each(function() {
if ($(this).is("[href]")) {
$(this).css("color", "blue");
}
});
实际应用示例
以下是一个完整的示例,展示如何检查元素是否包含特定文本、子元素或属性:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Contains Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
// 检查文本
$("p:contains('Hello')").css("color", "green");
// 检查子元素
$("div").has("span").css("background-color", "yellow");
// 检查属性
$("a[href]").css("font-weight", "bold");
});
</script>
</head>
<body>
<p>Hello World</p>
<p>Goodbye World</p>
<div><span>Span inside div</span></div>
<div>No span here</div>
<a href="https://example.com">Link with href</a>
<a>Link without href</a>
</body>
</html>
注意事项
:contains()选择器区分大小写。has()方法仅检查直接子元素,如果需要检查所有后代元素,使用find()。- 检查属性时,
attr()方法返回属性的值,而is()方法返回布尔值。






