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>
提交重置代码