如何使用 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.com/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 次檢視

啟動您的職業生涯

完成課程後獲得認證

開始
廣告