1

当我点击一个链接时,我需要找到下一个<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>

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

但这不起作用。我已经在 jsFiddle 中设置了代码

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

4

2 回答 2

5

尝试 :

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

或者

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

小提琴

您不能使用 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")。

库特西@TJ克劳德

于 2013-10-24T14:46:51.023 回答
3

使用.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');
于 2013-10-24T14:46:53.213 回答