当前位置:首页 > jquery

jquery 包含

2026-01-15 16:13:22jquery

jQuery 包含方法

jQuery 提供了多种方法来检查元素是否包含特定内容,包括文本、子元素或其他属性。以下是几种常用的方法:

检查元素是否包含特定文本

使用 :contains() 选择器或 text() 方法结合 JavaScript 的 includes() 方法:

jquery 包含

// 使用 :contains() 选择器
$("p:contains('特定文本')").css("color", "red");

// 使用 text() 和 includes()
$("p").each(function() {
  if ($(this).text().includes("特定文本")) {
    $(this).css("color", "red");
  }
});

检查元素是否包含特定子元素

使用 has() 方法或 find() 方法:

jquery 包含

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

标签: jquery
分享给朋友:

相关文章

jquery官网

jquery官网

jQuery 官网信息 jQuery 的官方网站是 jQuery.com,提供最新的 jQuery 版本下载、文档、教程和插件资源。 官网主要功能 下载 jQuery:提供压缩版(minifi…

jquery和vue的区别

jquery和vue的区别

jQuery 和 Vue.js 的区别 jQuery 和 Vue.js 是两种不同的前端技术,分别适用于不同的场景和开发需求。以下是它们的主要区别: 设计理念 jQuery 是一个轻量级的 Java…

react 如何引入jquery

react 如何引入jquery

引入 jQuery 到 React 项目 在 React 项目中引入 jQuery 可以通过多种方式实现,但需要注意 React 和 jQuery 操作 DOM 的方式可能冲突,因此建议仅在必要时使用…

jquery插件

jquery插件

jQuery 插件开发指南 jQuery 插件是一种扩展 jQuery 功能的模块化方式,允许开发者封装可重用的代码。以下是开发和使用 jQuery 插件的基本方法。 插件基本结构 jQuery 插…

jquery库

jquery库

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够…

jquery 面试题

jquery 面试题

jQuery 面试题常见考点 DOM 操作 选择器使用:$("#id"), $(".class"), $("tag") 元素增删改查:append(), remove(), html(),…