jQuery has() 方法



has() 方法用於選擇並返回包含一個或多個與指定選擇器匹配的子元素的所有元素。

注意: 要選擇包含多個巢狀元素的元素,請用逗號分隔選擇器。這允許您為要定位的元素指定多個條件。

語法

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

$(selector).has(element)

引數

此方法接受以下引數:

  • element:包含選擇器表示式或要匹配元素的元素的字串。

示例 1

在以下示例中,我們使用 jQuery 中的 has() 方法選擇所有包含 span 後代的 div 元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("div").has("span").css("border", "2px solid red");
});
</script>
</head>
<body>
<div>
  <p>This is a div with no spans.</p>
</div>
<div>
  <p>This is a div containing a <span>span element</span>.</p>
</div>
<div>
  <p>This is another div with no spans.</p>
</div>
</body>
</html>

當我們執行上述程式時,第二個 div 元素將被選中,因為它具有 span 後代。

示例 2

在這裡,我們選擇所有包含 span 元素的 divh2p 元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("div, h2, p").has("span").css("background-color", "green");
});
</script>
</head>
<body>
  <div>Div element <span>with span element </span>inside it.</div>
  <h2>Heading element <span>with span element </span>inside it.</h2>
  <p>Paragraph element with span element inside it.</p>
  <p>Paragraph element <span>with span element </span>inside it.</p>
  <p>Paragraph element <span>with span element </span>inside it.</p>  
</body>
</html>

如果我們執行上述程式,它將返回具有綠色背景顏色的選定元素。

示例 3

在此示例中,我們返回一個包含多個元素(ispanb)的元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("p").has("i, span, b").css("background-color", "yellow");
});
</script>
</head>
<body>
  <p>Paragraph element <i>with italic element </i>inside it.</p>
  <p>Paragraph element with <span>span </span>element inside it.</p>
  <p>Paragraph element with <b>bold</b> element inside it.</p>
  <p>Paragraph element</p>
</body>
</html>

如果我們執行上述程式,它將返回具有黃色背景顏色的選定元素。

jquery_ref_traversing.htm
廣告