jQuery:这个:“$(this).next()。next()”有效,但是“$(this).next('。div')”没有

时间:2015-05-16 21:55:49

标签: javascript jquery this next

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

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

当我键入它时,它可以工作:

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

但不是在我这样做的时候:

<head>

发生了什么使得第二个选项不起作用?我已经好几天了,不能把它弄清楚!感谢您的投入!

1 个答案:

答案 0 :(得分:44)

问题

如果您查看.next(selector)的{​​{3}},它就不会“找到”与选择器匹配的下一个兄弟。相反,它只是查看下一个兄弟,只有当它与你想要的选择器匹配时才会返回该元素。

以下是.next()的文档说明的内容:

  

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

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

使用.nextAll()

的解决方案

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

.box

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

创建自己的.findNext()方法

我经常想知道为什么jQuery没有一个方法可以让我自己创建一个:

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

然后你就可以使用:

// 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);
}

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

仅供参考,对此类问题的一种常见方法是在每组DOM元素周围放置一个包含div:

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

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

<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()元素。