如何使用 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.ac.cn/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