jQuery is() 方法



jQuery 中的 is() 方法用於確定所選元素是否與指定的選取器、元素或 jQuery 物件匹配。

此方法返回一個布林值:如果至少一個所選元素與指定條件匹配,則返回 “true”;如果沒有任何所選元素與指定條件匹配,則返回 “false”

語法

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

$(selector).is(selectorElement,function(index,element))

引數

此方法接受以下引數:

  • selectorElement:用於與所選元素匹配的選取器、元素或 jQuery 物件。
  • function(index, element):指定一個函式,用於對所選元素組執行。

示例 1

以下示例使用 is() 方法檢查段落元素是否可見,並相應地更改其背景顏色:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $('button').click(function(){
    if ($('p').is(':visible')) {
      $('p').css('background-color', 'green');
    } else {
      alert("Paragraph is hidden");
    }
  });
});
</script>
</head>
<body>
  <!--Paragraph is hidden-->
<p style="display: none;">This is a hidden paragraph.</p> 
<button>Check Visibility</button>
</body>
</html>

單擊按鈕時,會顯示一個警報,提示“段落隱藏”,因為<p> 定義為“display:none”。

示例 2

在此示例中,我們檢查指定的元素 (“a”) 是否為錨點標籤:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $('a').click(function(){
    if ($(this).is('a')) {
      alert('Clicked element is an anchor tag.');
    } else {
      alert('Clicked element is not an anchor tag.');
    }
  });
});
</script>
</head>
<body>
<a href="#">Click me to verify</a>
</body>
</html>

單擊按鈕時,會顯示一個警報,提示“單擊的元素是錨點標籤”,因為我們檢查的元素是錨點標籤。

示例 3

在下面的示例中,我們使用 parent() 和 is() 方法來確定 “ul” 是否是 “li” 元素的父元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $('li').click(function(){
    if ($(this).parent().is('ul')) {
      alert('Parent of li is ul.');
    } else {
      alert('Parent of li is NOT ul.');
    }
  });
});
</script>
</head>
<body>
<div>
  <ul>
    <li>Click me to verify if my parent is ul element.</li>
  </ul>
</div>
</body>
</html>

單擊按鈕後,會顯示一個警報,提示“li 的父元素是 ul”,因為元素 “li” 是 “ul” 元素的子元素。

jquery_ref_traversing.htm
廣告
© . All rights reserved.