jQuery选择相邻元素

use*_*890 5 jquery jquery-selectors

<li>
    <a class="handle" href="abc.htm">TopLink</a> 
    <ul class="container"> 
        <li> 
            <a href="xyz.htm">SubLink1</a> 
        </li>       
    </ul> 
</li>
Run Code Online (Sandbox Code Playgroud)

单击TopLink时(class ="handle");

问题:当我点击TopLink时,如何以这种方式编写jQuery选择器以选择ul class ="container"

就像是; $(this).(使用classname ="container"获取下一个UL)

Jam*_*ice 12

如果它始终是HTML的结构,您可以简单地使用next:

$(".handle").click(function() {
    var ul = $(this).next();
});
Run Code Online (Sandbox Code Playgroud)

如果链接和链接之间可能存在元素,则ul可以使用siblings获取与选择器匹配的所有元素:

$(".handle").click(function() {
    var uls = $(this).siblings("ul.container");
});
Run Code Online (Sandbox Code Playgroud)

虽然这也会得到前面的兄弟姐妹.要获得以下兄弟姐妹,您可以使用nextAll:

$(".handle").click(function() {
    var uls = $(this).nextAll("ul.container");

    //You can then use `.eq(0)` to get the closest matching sibling:
    var sibling = uls.eq(0);
});
Run Code Online (Sandbox Code Playgroud)