如何使用jQuery查找具有ID属性的下一个元素

Dig*_*ift 1 html javascript jquery siblings jquery-selectors

当我点击链接时,我需要找到<section>具有ID属性的下一个并返回其ID.

所以给定以下标记和javascript,我希望点击链接将"section_3"写入控制台.

<section id="section_1">
    <a href="#" class="findNext">Find</a>
</section>
<section></section>
<section id="section_3"></section>
<section id="section_4"></section>
Run Code Online (Sandbox Code Playgroud)

$('a.findNext').click(function() {
    var nextSectionWithId = $(this).closest("section").next("section[id]");
    if (nextSectionWithId) {
        var sectionId = nextSectionWithId.attr('id');
        console.log(sectionId)
    }
});
Run Code Online (Sandbox Code Playgroud)

但这不起作用.我在jsFiddle中设置了代码.

任何想法为什么这不起作用?

PSL*_*PSL 5

试试:

var nextSectionWithId = $(this).closest("section").nextAll("section[id]:first");
Run Code Online (Sandbox Code Playgroud)

要么

var nextSectionWithId = $(this).closest("section").nextAll("section[id]").filter(':first');
Run Code Online (Sandbox Code Playgroud)

小提琴

您不能使用next,因为next将仅在下一个元素中查找匹配项.所以你可以改为使用nextAll结合:首先在选择器中.

更新

您可以在jquery中使用first()方法来获取集合中的第一个元素,这似乎是一个更快的选项.

var nextSectionWithId = $(this).closest("section").nextAll("section[id]").first();
Run Code Online (Sandbox Code Playgroud)

可能是这个原因:

因为:首先是jQuery扩展而不是CSS规范的一部分,查询使用:首先不能利用本机DOM querySelectorAll()方法提供的性能提升.要在使用时获得最佳性能:首先选择元素,首先使用纯CSS选择器选择元素,然后使用.filter(":first").

Coutesy @TJ克劳德