【问题标题】:jQuery: this: "$(this).next().next()" works, but "$(this).next('.div')" does NotjQuery: this: "$(this).next().next()" 有效,但 "$(this).next('.div')" 无效
【发布时间】:2015-07-28 15:45:54
【问题描述】:

好的,我正在尝试让这组信息单独隐藏。

<img class="arrow" src="images/navigation/arrowright.png">
<H2>More Information</H2>
<div class="box">
    <h2>Bibendum Magna Lorem</h2>
    <p>Cras mattis consectetur purus sit amet fermentum.</p>
</div>

<img class="arrow" src="images/navigation/arrowright.png">
<H2>A Second Group of Information</H2>
<div class="box">
    <h2>Bibendum Magna Lorem</h2>
    <p>Cras mattis consectetur purus sit amet fermentum.</p>
</div>

当我输入这个时它工作:

$(".arrow").click(function() {
    $(this).next().next().slideToggle();
});

但不是在我这样做时:

$(".arrow").click(function() {
    $(this).next('.box').slideToggle();
});

发生了什么导致第二个选项不起作用?我已经搞了好几天了,还是搞不懂!感谢您的意见!

【问题讨论】:

  • 仅供参考,HTML 的缩进使您看起来在实际上不存在的元素之间存在父/子关系(显示 HTML 的一种误导方式)。
  • 啊,是的,这是有道理的,完全是我的错!我对此很陌生,所以我仍然习惯了一切。谢谢你的指点!

标签: javascript jquery this next


【解决方案1】:

问题

如果您查看documentation.next(selector),它不会“找到”与选择器匹配的下一个兄弟。相反,它只查看下一个同级元素,并且仅在它与不是您想要的选择器匹配时才返回该元素。

.next() 的文档是这样说的:

描述:获取每个元素的紧随其后的兄弟元素 匹配元素的集合。如果提供了选择器,它将检索 仅当它与该选择器匹配时才是下一个兄弟。

因此,您可以看到 .next(".box") 将查看紧跟在您的 .arrow 元素(即下一个兄弟元素)之后的 h2 元素,然后将其与 .box 选择器进行比较,因为它们没有t 匹配,它将返回一个空的 jQuery 对象。


使用 .nextAll() 的解决方案

如果你想要下一个匹配选择器的兄弟,你可以使用这个:

$(this).nextAll(".box").eq(0).slideToggle();

这会找到所有匹配选择器的兄弟姐妹,然后只提取第一个。


创建自己的 .findNext() 方法

我经常想知道为什么 jQuery 没有我自己制作的方法:

// get the next sibling that matches the selector
// only processes the first item in the passed in jQuery object
// designed to return a jQuery object containing 0 or 1 DOM elements
jQuery.fn.findNext = function(selector) {
    return this.eq(0).nextAll(selector).eq(0);
}

然后,您只需使用:

$(this).findNext(".box").slideToggle();

选项:向 HTML 添加更多结构以使事情更简单、更灵活

仅供参考,解决此类问题的常用方法是在每组 DOM 元素周围放置一个包含 div,如下所示:

<div class="container">
    <img class="arrow" src="images/navigation/arrowright.png">
    <H2>More Information</H2>
    <div class="box">
            <h2>Bibendum Magna Lorem</h2>
            <p>Cras mattis consectetur purus sit amet fermentum.</p>
    </div>
</div>

<div class="container">
     <img class="arrow" src="images/navigation/arrowright.png">
     <H2>A Second Group of Information</H2>
     <div class="box">
            <h2>Bibendum Magna Lorem</h2>
            <p>Cras mattis consectetur purus sit amet fermentum.</p>
     </div>    
</div>

然后,您可以使用对元素的精确定位不太敏感的代码:

$(".arrow").click(function() {
    $(this).closest(".container").find(".box").slideToggle();
});

这使用.closest() 上升到包含和公共父级,然后使用.find() 在该组中查找.box 元素。

【讨论】:

  • 更具表现力:$(this).nextAll(".box").first().slideToggle();
  • “更多的 HTML 结构让事情变得更简单、更灵活”
猜你喜欢
  • 2013-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-28
  • 2017-07-25
  • 1970-01-01
  • 2013-06-30
  • 1970-01-01
相关资源
最近更新 更多