如何在类选择器中使用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://cdn.staticfile.org/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>热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短