如何使用 jQuery 中的 jQuery.closest() 方法?
closest() 方法從當前元素開始,只返回與所傳遞表示式匹配的第一個祖先。此返回的 jQuery 物件具有零或一個元素。
示例
你可以嘗試執行以下程式碼,瞭解如何使用 jQuery closest 方法
<!DOCTYPE html>
<html>
<head>
<style>
.myclass * {
display: block;
border: 2px solid blue;
color: red;
padding: 5px;
margin:10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("span").closest("ol").css({"color": "gray", "border": "3px solid yellow"});
});
</script>
</head>
<body class="myclass">body
<div style="width:500px;">div
<ol>ol - This is the third ancestor
<ol>ol - This is the second ancestor
<ol>ol - This is the first ancestor
<li>li - This is the direct parent element
<span>demo</span>
</li>
</ol>
</ol>
</ol>
</div>
</body>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP