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如何判断checkbox是否选中

ajax与jQuery的区别是什么

jQuery怎么禁用a标签

jQuery addclass不起作用怎么办

jQuery怎么判断radio是否选中

如何解决jQuery不兼容问题

jQuery绑定事件有几种方式?

jQuery怎么取消css样式

jQuery mobile怎么样

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




打赏

取消

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

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

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

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

评论

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