好吧,我在试着把这组信息单独隐藏起来。
<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();
});是什么原因导致第二种选择不起作用?我已经做了好几天了,都他妈的想不出来!非常感谢您的意见!
发布于 2015-05-17 05:57:23
The Problem
如果您查看.next(selector)的documentation,它不会“找到”与选择器匹配的下一个同级。相反,它只查看下一个同级元素,如果元素与您想要的选择器匹配,则只返回该元素。
以下是.next()的医生说的话:
描述:获取匹配元素集合中每个元素紧跟其后的同级元素。如果提供了选择器,则仅当与该选择器匹配时才检索下一个同级。
因此,您可以看到,.next(".box")将查看紧跟在.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,如下所示:
<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元素。
https://stackoverflow.com/questions/30281166
复制相似问题