JQuery CSS nth-child选择器

时间:2013-06-27 07:58:42

标签: jquery css

我正面临着nth-child选择器非常奇怪的行为。

当我调用函数 BackColor1()时,我的视觉效果如下: enter image description here

出了什么问题。如果我打电话给 BackColor2(),一切看起来都不错。

enter image description here

有人可以通过 BackColor1()函数解释诀窍在哪里以及我做错了什么?

这是我的示例HTML

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        //BackColor1();
        //BackColor2();
    });
    function BackColor1() {
        $("li:nth-child(2n+1) > div").css({ "background": "#F2F2F2" });
    }

    function BackColor2() {
        $("li").each(function (key, val) {                
            if (key % 2 == 0) {
                $(this).children("div").css({ "background": "#F2F2F2" });
            }
        });
    }
</script>
</head>
<body>
<ul>            
    <li>
        <div>Video Streaming</div>
        <ul>                            
            <li><div>VOD</div></li>                            
            <li><div>Progressive Streaming</div></li>                                                                        
        </ul>                            
    </li>                    
    <li><div>Middle Lesson Without Chapter</div></li>                    
    <li>
        <div>File Download</div>                        
        <ul>                            
            <li><div>Direct Download</div></li>                            
        </ul>                            
    </li>                    
    <li><div>Pre Last Lesson Without Chapter</div></li>                    
    <li><div>Last Lesson Without Chapter</div></li>
</ul>
</body>
</html>

4 个答案:

答案 0 :(得分:2)

您应该使用even selector

代码:

function BackColor1() {
    $("li:even > div").css({
        "background": "#F2F2F2"
    });
}

demo

答案 1 :(得分:0)

这是因为VOD项目是其父项的第一个子项,因此接收颜色。它没有考虑到它周围的其他元素。

但是,您的jQuery选择器正在将页面上的所有列表项视为一个大组,因此无论它们在DOM中的哪个位置都会交替显示颜色。

答案 2 :(得分:0)

BackColor one使用第n个子选择器...每个元素的子编号都是根据其父编号所以当你嵌套列表时,你很容易面对多个LI元素被视为nth-child = 1等等。

答案 3 :(得分:0)

这只是因为nth-child从头开始计算每个ul

<ul>            
    <li> <!-- first child of parent ul-->
        <div>Video Streaming</div>
        <ul>                            
            <li><div>VOD</div></li> <!-- first child of nested ul-->
        </ul>                            
    </li>                    
    <li><div>Middle Lesson Without Chapter</div></li> <!-- second child of parent ul-->
    ...
相关问题