fja*_*xyu 17 javascript jquery this next
好的,我试图让这组信息单独隐藏.
<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>
Run Code Online (Sandbox Code Playgroud)
当我键入它时它可以工作:
$(".arrow").click(function() {
$(this).next().next().slideToggle();
});
Run Code Online (Sandbox Code Playgroud)
但不是我这样做的时候:
$(".arrow").click(function() {
$(this).next('.box').slideToggle();
});
Run Code Online (Sandbox Code Playgroud)
发生了什么让第二种选择不起作用?我已经好几天了,不能把它弄清楚!感谢您的投入!
jfr*_*d00 45
问题
如果你看一下文档的.next(selector),它没有"发现"的选择相匹配的下一个同级.相反,它只看下一个兄弟,如果匹配的选择器不是你想要的,那么它只返回该元素.
以下是doc .next()所说的内容:
描述:获取匹配元素集中每个元素的紧随其后的兄弟.如果提供了选择器,则仅当它与该选择器匹配时,它才会检索下一个兄弟.
因此,您可以看到.next(".box")将查看h2紧跟在元素后面的.arrow元素(即下一个兄弟元素),然后将其与.box选择器进行比较,因为它们不匹配,它将返回一个空的jQuery对象.
使用.nextAll()的解决方案
如果您想要与选择器匹配的下一个兄弟,您可以使用:
$(this).nextAll(".box").eq(0).slideToggle();
Run Code Online (Sandbox Code Playgroud)
这会找到跟随选择器的所有兄弟姐妹,然后只提取第一个.
创建自己的.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);
}
Run Code Online (Sandbox Code Playgroud)
然后,你只需使用:
$(this).findNext(".box").slideToggle();
Run Code Online (Sandbox Code Playgroud)
选项:向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>
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用对元素的精确定位稍微不敏感的代码:
$(".arrow").click(function() {
$(this).closest(".container").find(".box").slideToggle();
});
Run Code Online (Sandbox Code Playgroud)
这取决于使用的包含和公共父级.closest(),然后用于.find()查找该.box组中的 元素.