jQuery——获取某个元素兄弟元素的相关方法

时间:2025-03-06 18:21:15
    <style>
        ul{
            list-style-type: none;
            cursor: pointer;
        }
    </style>
    <script src="jquery-1.12."></script>
    <script>
        //获取某个li的下一个兄弟元素
        $(function(){
            $("third").click(function(){
                $(this).next().css("backgroundColor","yellowgreen");
                //获取某个li的前一个兄弟元素
                $(this).prev().css("backgroundColor","greenyellow");
                //获取某个li的后面的所有的兄弟元素
                $(this).nextAll().css("backgroundColor","red");
                //获取某个li的前面的所有的兄弟元素
                $(this).prevAll().css("backgroundColor","red");
                //获取当前li的所有兄弟元素
                $(this).siblings("li").css("backgroundColor","gray");
            });
        });
    </script>
</head>
<body>
<ul id="uu">
    <li>终于结束的起点</li>
    <li>成名在望</li>
    <li id="third">少年他的奇幻漂流</li>
    <li>任意门</li>
    <li>如果我们不曾相遇</li>
    <li>转眼</li>
</ul>
</body>

案例:

    <script src="jquery-1.12."></script>
    <script>
        $(function(){
            $("ul>li").mouseenter(function(){//鼠标进入事件
                $(this).css("backgroundColor","red").siblings("li").css("backgroundColor","");
            }).mouseleave(function(){//鼠标离开事件
                $(this).css("backgroundColor","");
            }).click(function(){//点击事件
                $(this).prevAll("li").css("backgroundColor","yellow");
                $(this).nextAll("li").css("backgroundColor","blue");
            });
        });
    </script>
......
	<ul id="uu">
    	<li>终于结束的起点</li>
    	<li>成名在望</li>
    	<li id="third">少年他的奇幻漂流</li>
    	<li>任意门</li>
    	<li>如果我们不曾相遇</li>
    	<li>转眼</li>
	</ul>

断链:
对象调用方法之后,返回的已经不是当前这个对象了,此时再调用方法,就出现了断链
.end()方法是修复断链,恢复断链之前的状态,一般不推荐链式编程

$(this).prevAll("li").css("backgroundColor","yellow").end().nextAll("li").css("backgroundColor","blue");