jQuery hasClass() 方法



jQuery 中的 hasClass() 方法用於檢查任何選定的元素是否具有指定的類名。它檢查 jQuery 物件中的任何元素是否具有指定的類名。

語法

以下是 jQuery 中 hasClass() 方法的語法:

$(selector).hasClass(classname)

引數

此方法接受以下引數:

  • classname: 表示要檢查的類名的字串。

返回值

如果任何選定的元素具有指定的類名,則該方法返回 true;否則,返回 false。

示例 1

在下面的示例中,我們使用 hasClass() 方法來檢查任何 <div> 元素是否具有名為“highlight”的類:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    if ($('div').hasClass('highlight')) {
        alert("A div with the class 'highlight' exist.");
    } else {
        alert("A div with the class 'highlight' does not exist.");
    }
  })
});
</script>
</head>
<body>
<div class="highlight">Div element with class "highlight".</div>
<div class="one">Div element with class "one".</div>
<div class="two">Div element with class "two".</div>
<button>Click to check</button>
</body>
</html>

當我們單擊按鈕時,它會返回一個警報,指出存在一個名為“highlight”的類的 <div> 元素。

示例 2

在這裡,我們檢查任何 <p> 元素是否具有名為“highlight”的類:

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $('p').each(function(){
      if ($(this).hasClass('highlight')) {
        $(this).css("background-color", "yellow");
      }
    });
  });
});
</script>
</head>
<body>
<p class="highlight">Paragraph element with class "highlight".</p>
<p class="one">Paragraph element with class "one".</p>
<p class="two">Paragraph element with class "two".</p>
<button>Click to check</button>
</body>
</html>

單擊按鈕後,它會將具有名為“highlight”的類的 <p> 元素突出顯示為黃色背景。

jquery_ref_html.htm
廣告
© . All rights reserved.