简体   繁体   English

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

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

When I click on a link, I need to find the next <section> that has an ID attribute and return its ID. 当我单击链接时,我需要找到具有ID属性的下一个<section>并返回其ID。

So given the following markup and javascript, I would expect clicking on the link to write "section_3" to the console. 因此,考虑到以下标记和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>

and

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

But this doesn't work. 但这是行不通的。 I have set the code up here in jsFiddle . 我已经在jsFiddle中设置了代码

Any ideas why this is not working? 任何想法为什么这不起作用?

Try : 尝试:

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

or 要么

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

Fiddle 小提琴

You cannot use next because next will look for a match only in the next element. 您不能使用next,因为next仅在next元素中查找匹配项。 So you can instead use nextAll combined with :first in the selector. 因此,您可以在选择器中将nextAll:first结合使用。

Update 更新资料

You can use the first() method in jquery to fetch the first element in the collection as well which seems like a faster option. 您也可以在jquery中使用first()方法来获取集合中的第一个元素,这似乎是一个更快的选择。

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

Probably could be this reason: 可能是这个原因:

Because :first is a jQuery extension and not part of the CSS specification, queries using :first cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. 因为:first是jQuery扩展,而不是CSS规范的一部分,所以使用:first的查询无法利用本机DOM querySelectorAll()方法提供的性能提升。 To achieve the best performance when using :first to select elements, first select the elements using a pure CSS selector, then use .filter(":first"). 为了在使用:first选择元素时达到最佳性能,请首先使用纯CSS选择器选择元素,然后使用.filter(“:first”)。

Coutesy @TJ Crowder Coutesy @TJ人群

Use .nextAll() 使用.nextAll()

DEMO 演示

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

DEMO 演示

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

DEMO 演示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM