比较jQuery:nth-of-type() 选择器和:nth-child()选择器

1,说明:type : 类型
child : 孩子
代码说明:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>选择器比较</title>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js" type="text/javascript" charset="utf-8"></script>
    <script>
        $(function() {
                    var ys1 = $('li:nth-child(2)');
                    ys1.css({
                        width: '100px',
                        height: '100px',
                        backgroundColor: 'red',
                    });
                }
    </script>
</head>

<body>
    <ul>
        <li>01</li>
        <span>02</span>
        <li>03</li>
        <li>04</li>
    </ul>
</body>

</html>

运行结果:

在这里插入图片描述

 <script>
        $(function() {
                    var ys1 = $('li:nth-of-type(2)');
                    ys1.css({
                        width: '100px',
                        height: '100px',
                        backgroundColor: 'red',
                    });
                }

运行结果:
在这里插入图片描述
总结: :nth-child()选择器,若第n个孩子不是指定的元素,则不会被选中。
nth-of-type()选择器,是在指定的类型中选取。

猜你喜欢

转载自blog.csdn.net/weixin_42056687/article/details/107501156
今日推荐