前端开发tips:JS查找已知类的父类。定一个html文档,如何在给定类名的帮助下获取元素的父类。
方法1:使用closest()方法
● on()方法用于为所选元素选择事件处理程序;这意味着当用户单击按钮然后调用函数。
● closest()方法用于返回所选元素的第一个祖先。
示例:使用closest()方法获取元素的第一个匹配的祖先。
<!DOCtype HTML> <html> <head> <meta charset="utf-8"> </head> <body style="text-align:center;"> <p style= "font-size: 17px; font-weight: bold;">点击按钮,查看结果</p> <div class="parent"> <div class="child"></div> </div> <button>点击</button> <p id="DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script src="https://code.JQuery.com/jQuery-3.3.1.min.js"></script> <script> $('button').on('click', function() { var Object = $('.child').closest('.parent'); if (object.length) { $('#DOWN').text("className = '.child'" + ",parentName = '.parent'"); } else { $('#DOWN').text("不存在父类"); } }); </script> </body> </html>
在这个例子中, $("span").closest("ul") 指我们查找一个span元素的第一个ul祖先。最靠近span的祖先是li,但是由于查到一个div,jquery 跳过li元素继续查找下一个祖先,直到它找出我们要查找的ul.假如我们用parents() 方法替代,它将返回ul的祖先 。

方法2:使用parent()方法
● on()方法用于为所选元素选择事件处理程序;这意味着当用户单击按钮然后调用函数。
● parent()方法用于返回被选元素的直接父元素。
示例:使用parent()方法获取元素的直接父元素。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.ancestors *{
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
}
</style>
<script src="https://CDN.staticfile.org/jquery/1.10.2/JQuery.min.js">
</script>
<script>
$(document).ready(function(){
$("span").parent("li").CSS({"color":"red","border":"2px solid red"});
});
</script>
</head>
<body class="ancestors">body (曾曾祖父节点)
<div style="width:500px;">div (曾祖父节点)
<ul>ul (祖父节点)
<li>li (直接父节点)
<span>span</span>
</li>
<li>li (直接父节点)
<span>span</span>
</li>
</ul>
</div>
</body>
</html>


网友评论文明上网理性发言 已有0人参与
发表评论: