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

How to find the next element which has an ID attribute using jQuery

本文关键字:属性 下一个 元素 ID 何使用 jQuery 查找      更新时间:2023-09-26

当我单击链接时,我需要找到下一个具有 ID 属性的<section>并返回其 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>

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

但这行不通。我已经在jsFiddle中设置了代码。

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

尝试:

var nextSectionWithId = $(this).closest("section").nextAll("section[id]:first");

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

小提琴

您不能使用 next,因为 next 将仅在 next 元素中查找匹配项。因此,您可以在选择器中将 nextAll 与 :first 结合使用。

更新

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

var nextSectionWithId = $(this).closest("section").nextAll("section[id]").first();

可能是这个原因:

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

库特西 @T.J. 克劳德

使用 .nextAll()

演示

var nextSectionWithId = $(this).closest("section").nextAll("section[id]")[0].id;

演示

var nextSectionWithId = $(this).closest("section").nextAll("section[id]").eq(0).attr('id');

演示

var nextSectionWithId = $(this).closest("section").nextAll("section[id]").attr('id');