本文摘自PHP中文网,作者coldplay.xixi,侵删。
jquery查找指定元素父类的方法:1、使用【closest()】方法用于返回所选元素的第一个祖先;2、使用【parent()】方法用于返回被选元素的直接父元素。
本教程操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。
推荐:jquery视频教程
jquery查找指定元素父类的方法:
在jquery中可以使用closest()方法、parent()方法来查找指定元素的父类。
示例1:使用closest()方法获取元素的第一个匹配的祖先。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <!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>
|
效果图:
阅读剩余部分
相关阅读 >>
jQuery中的美元符号$有什么作用
jQuery如何判断checkbox是否选中
ajax与jQuery的区别是什么
jQuery怎么禁用a标签
jQuery addclass不起作用怎么办
jQuery怎么判断radio是否选中
如何解决jQuery不兼容问题
jQuery绑定事件有几种方式?
jQuery怎么取消css样式
jQuery mobile怎么样
更多相关阅读请进入《jQuery》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » jquery如何查找指定元素的父类