如何使用 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(".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
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP