jQuery層次選擇器

層次選擇器


#$(s1  s2) [父子]

衍生選擇器:在s1內部取得全部的s2節點(不考慮層次)

$(“div  span”)

<div>
    <span></span>
    <p>
        <span></span>
    </p>
</div>
<span></span>

$(s1 > s2) [父子]

直接子元素選擇器:在s1內部獲得s2的子元素節點

$(“div > span”)

    <div>
        <span></span>
        <p>
            <span></span>
        </p>
        <span></span>
    </div>
<span></span>

$(s1 + s2) [兄弟]

直接兄弟選擇器:在s1後邊獲得緊緊挨著的第一個兄弟關係的s2節點,s1和s2之間不能有任何其它標籤,不然不起作用

$(“div + span”)

<div>
    <span></span>
    <p>
        <span></span>
    </p>
    <span></span>
</div>
<span></span>
<span></span>
<div></div>
<span></span>


$(s1 ~ s2 ) [兄弟]

後續全部兄弟關係節點選擇器:在s1後邊獲得全部兄弟關係的s2節點

$(“div ~ span” )

<div>
    <span></span>
    <p>
        <span></span>
    </p>
    <span></span>
</div>
<span></span>
<span></span>
<p></p>
<span></span>
<!DOCTYPE html>
<html>
    <head>
        <title>php.cn</title>
        <meta charset="utf-8" />
        <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
        <script >
        function f1(){
            //$(s1 s2)
            $('div span').css('background-color','blue');

            //$(s1 > s2) 
            $('div > span').css('background-color','green');//张飞 关羽

            //$(s1 + s2) 紧紧挨着的
            $('div + span').css('background-color','red');

            //$(s1 ~ s2)
           $('div ~ span').css('background-color','brown');
        }
        </script>
    </head>
    <body>
        <h2>层次选择器</h2>
        <div>
            <span>北京</span>
            <p>
                <span>上海</span>
            </p>
            <span>深圳</span>
        </div>
        <p>南京</p>
        <span>杭州</span>
        <p>厦门</p>
        <span>天津</span>
        <div>重庆</div>
        <span>合肥</span>
        <input type="button" value="触发" onclick="f1()" />
    </body>
</html>

#:請大家將四個選擇器的其它三個註解掉。一個一個進行測試

繼續學習
||
<!DOCTYPE html> <html> <head> <title>php.cn</title> <meta charset="utf-8" /> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script > function f1(){ //$(s1 s2) $('div span').css('background-color','blue'); //$(s1 > s2) $('div > span').css('background-color','green');//张飞 关羽 //$(s1 + s2) 紧紧挨着的 $('div + span').css('background-color','red'); //$(s1 ~ s2) $('div ~ span').css('background-color','brown'); } </script> </head> <body> <h2>层次选择器</h2> <div> <span>北京</span> <p> <span>上海</span> </p> <span>深圳</span> </div> <p>南京</p> <span>杭州</span> <p>厦门</p> <span>天津</span> <div>重庆</div> <span>合肥</span> <input type="button" value="触发" onclick="f1()" /> </body> </html>