当前位置:首页 > jquery

jquery 包含

2026-01-15 16:13:22jquery

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");
  }
});

实际应用示例

以下是一个完整的示例,展示如何检查元素是否包含特定文本、子元素或属性:

jquery 包含

<!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() 方法返回布尔值。

标签: jquery
分享给朋友:

相关文章

jquery文档

jquery文档

以下是关于 jQuery 文档的核心资源和使用方法整理: jQuery 官方文档 jQuery 官方文档是学习和使用 jQuery 最权威的资源,包含详细的 API 说明、示例和更新日志。…

jquery文档

jquery文档

以下是关于 jQuery 文档的核心内容和资源整理,便于快速查阅和使用: jQuery 官方文档 官网地址:jQuery Official Documentation 内容分类:API 参考…

jquery 获取

jquery 获取

jQuery 获取元素的方法 jQuery 提供了多种方法来获取 DOM 元素,以下是常用的几种方式: 通过 ID 获取元素 使用 $("#id") 可以获取指定 ID 的元素。例如: $("#m…

jquery方法

jquery方法

jQuery 核心方法 $() 或 jQuery() 是核心选择器方法,用于获取 DOM 元素或创建 jQuery 对象。支持 CSS 选择器、DOM 元素或 HTML 字符串。 $('#id'…

jquery 节点

jquery 节点

jQuery 节点操作 jQuery 提供了丰富的 DOM 节点操作方法,可以轻松实现节点的增删改查。 查找节点 使用选择器查找节点是最常见的操作。jQuery 支持 CSS 选择器语法,可以快速定…

jquery点击事件

jquery点击事件

jQuery 点击事件基础用法 使用 jQuery 绑定点击事件主要通过 .click() 方法或 .on() 方法实现。以下示例展示如何为按钮添加点击事件: // 方法1: 使用 .click()…