jQuery closest() 方法



jQuery 中的 closest() 方法用於向上遍歷 DOM 樹,查詢與指定選擇器匹配的所選元素的最近祖先元素。

此方法從當前元素向上遍歷 DOM 樹,查詢與選擇器匹配的祖先元素。它返回第一個與選擇器匹配的元素,從當前元素本身開始,然後向上移動。如果找不到匹配項,則遍歷將一直持續到文件根。

即使多個元素與選擇器匹配,也只返回遇到的第一個元素。

語法

以下是 jQuery 遍歷 closest() 的語法:

$(selector).closest(filter)

引數

此方法接受以下引數:

  • filter: 選擇每個選定元素的最近祖先元素,該祖先元素與指定的選擇器匹配。

示例 1

在下面的示例中,我們演示瞭如何使用 closest() 方法在單擊其內部的按鈕時查詢最近的祖先 <div> 元素:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        var closestDiv = $(this).closest("div");
        closestDiv.css("background-color", "lightblue");
    });
});
</script>
<style>
    div {
        border: 1px solid black;
        padding: 10px;
        margin: 10px;
    }
</style>
</head>

<body>
<div>
    <p>This is the third div element.</p>
  <div>
    <p>This is the second div element.</p>
    <div>
      <p>This is the first div.</p>
      <button>Click to highlight closest div</button>
    </div>
  </div>
</div>
</body>
</html>

單擊 <div> 內的按鈕後,最近的祖先 <div> 將以淺藍色背景顏色突出顯示。

jquery_ref_traversing.htm
廣告
© . All rights reserved.