jquery如何查找指定元素的父类


本文摘自PHP中文网,作者coldplay.xixi,侵删。

jquery查找指定元素父类的方法:1、使用【closest()】方法用于返回所选元素的第一个祖先;2、使用【parent()】方法用于返回被选元素的直接父元素。

本教程操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。

推荐:jquery视频教程

jquery查找指定元素父类的方法:

在jquery中可以使用closest()方法、parent()方法来查找指定元素的父类。

  • 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 $是什么用法

jQuery怎么添加css样式

jQuery出现中文乱码怎么解决

jQuery a标签不可用的实现方法

jQuery收费吗?

jQuery有哪些过滤选择器?

jQuery三大版本之间有什么区别?

jQuery怎么遍历数组

jQuery怎么样判断是否为空

更多相关阅读请进入《jQuery》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...

    正在狠努力加载,请稍候...