jQuery:这个:“$(this).next()。next()”有效,但是“$(this).next(’。div’)”没有
好的,我试图让这组信息单独隐藏。
More Information
Bibendum Magna Lorem
Cras mattis consectetur purus sit amet fermentum.
A Second Group of Information
Bibendum Magna Lorem
Cras mattis consectetur purus sit amet fermentum.
当我键入它时它工作:
$(".arrow").click(function() { $(this).next().next().slideToggle(); });
但不是我这样做的时候:
$(".arrow").click(function() { $(this).next('.box').slideToggle(); });
发生了什么让第二种选择不起作用? 我已经好几天了,不能把它弄清楚! 感谢您的投入!
问题
如果查看.next(selector)
的文档 ,它不会“找到”与选择器匹配的下一个兄弟。 相反,它只是查看下一个兄弟,如果它匹配的选择器不是你想要的,那么它只返回该元素。
这是.next()
的文档说的:
描述:获取匹配元素集中每个元素的紧随其后的兄弟。 如果提供了选择器,则仅当它与该选择器匹配时,它才会检索下一个兄弟。
所以,您可以看到.next(".box")
将查看紧跟在.arrow
元素.arrow
的h2
元素(即下一个兄弟元素),然后将其与.box
选择器进行比较,因为它们不匹配,它将返回一个空的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,如下所示:
More Information
Bibendum Magna Lorem
Cras mattis consectetur purus sit amet fermentum.
A Second Group of Information
Bibendum Magna Lorem
Cras mattis consectetur purus sit amet fermentum.
然后,您可以使用对元素的精确定位稍微不敏感的代码:
$(".arrow").click(function() { $(this).closest(".container").find(".box").slideToggle(); });
这将使用.closest()
进行包含和公共父.closest()
,然后使用.find()
查找该组中的.box
元素。