当前位置:首页 > 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");
  }
});

实际应用示例

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

<!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官网(https://jquery.com/),点击页面中的“Download”按钮。提供两个版本选择: Production版本:压缩后的…

jquery 菜鸟

jquery 菜鸟

以下是针对 jQuery 初学者的基础指南,涵盖核心概念和常用操作: jQuery 简介 jQuery 是一个快速、轻量级的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画和…

jquery中

jquery中

jQuery 基础概念 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。其核心特点是“写得更少,做得更多”(Write L…

jquery选择

jquery选择

jQuery选择器基础 jQuery选择器基于CSS选择器语法,用于快速定位和操作DOM元素。通过$()或jQuery()函数传入选择器字符串实现。 常见选择器类型: 元素选择器:$("p") 选…

jquery对象

jquery对象

jQuery 对象简介 jQuery 对象是通过 jQuery 选择器或方法创建的封装了 DOM 元素集合的对象。它提供了一系列便捷的方法来操作 DOM、处理事件、实现动画等。与原生 DOM 对象不同…

下载jquery

下载jquery

下载 jQuery 的方法 官方网站下载 访问 jQuery 的官方网站 https://jquery.com,点击页面上的“Download”按钮。选择压缩版(minified)或未压缩版(unco…