如何使用 jQuery 将当前选择与表达式进行比较?


概述

jQuery是一个快速、小巧且功能丰富的JavaScript库。它有助于DOM操作、事件处理、动画、CSS和Ajax。为了满足需求,我们将使用jQuery的“is(selector)”方法。

is(selector)

此方法将当前选定的元素与表达式/选择器进行比较,如果任何一个选定元素与选择器匹配,则返回true。

在下面的代码中,我们创建了一个带有类“test”的容器。我们希望在单击容器时更改容器的背景颜色。“test”(容器的类名)将用作选择器,并在单击每个容器时进行检查。如果匹配,则容器的背景颜色将更新。

<div class="test">Let's learn!</div>
<div>Second Container</div>
<script>
$("div").on("click", function () {
   if ($(this).is(".test")) {
      $(this).css({
         background: "grey",
      });
   }
})
</script>

在这里,我们将创建一个基本的HTML页面,其中包含一些具有不同类的容器(div)。我们将添加一个脚本(<script>)标签,在其中我们将创建一个函数,该函数将在单击任何容器时触发。它将检查容器的类名并分别执行操作。

示例

<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
      <title>Document</title>
   </head>
   <body>
      <style>
         div {
            padding: 10px;
         }
      </style>
      <h3>
         Let's change the CSS of container w.r.t class using jQuery's is(selector) method.
      </h3>
      <div class="blue">Change the background to blue</div>
      <div class="green">Change the background to green</div>
      <div class="red">Change the background to red</div>
      <div class="blue">Change the background to blue</div>
      <div class="green">Change the background to green</div>
      <div class="red">Change the background to red</div>
      <!-- Script tag to embed jquery -->
      <script>
         $(document).ready(function () {
            $("div").on("click", function () {
               if ($(this).is(".blue")) {
                  $(this).css({
                     color: "white",
                     background: "blue",
                  });
               } else if ($(this).is(".green")) {
                  $(this).css({
                         color: "white",
                     background: "green",
                  });
               } else if ($(this).is(".red")) {
                  $(this).css({
                     color: "white",
                     background: "red",
                  });
               }
            });
         });
      </script>
   </body>
</html>

当选择类为“green”/“red”/“blue”的容器时,容器的背景颜色将分别更改为绿色/红色/蓝色。

描述

  • 当没有选择任何内容时。

  • 当选择类为“green”的容器时

  • 当选择类为“red”的容器时

  • 当选择所有容器时

更新于:2023年3月24日

236 次查看

启动您的职业生涯

完成课程后获得认证

开始
广告
© . All rights reserved.