如何將jQuery.closest()方法與類選擇器結合使用?
closest() 方法從當前元素開始,僅返回與傳遞表示式匹配的第一個祖先。返回的 jQuery 物件包含 0 或 1 個元素。使用類選擇器很容易,請參閱下方內容,瞭解如何使用。
示例
你可以嘗試執行以下程式碼,以瞭解如何將 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(".one").css({"color": "maroon", "border": "5px solid maroon"});
});
</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
<li>li - This is the direct parent element
<span>demo</span>
<span class="one">demo - using class selector with closest() method</span>
</li>
</ol>
</ol>
</div>
</body>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP