首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery: this:"$(this).next().next()“有效,但"$(this).next('.div')”无效

jQuery: this:"$(this).next().next()“有效,但"$(this).next('.div')”无效
EN

Stack Overflow用户
提问于 2015-05-17 05:55:49
回答 1查看 49.3K关注 0票数 19

好吧,我在试着把这组信息单独隐藏起来。

代码语言:javascript
复制
<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>

当我键入以下内容时,它会起作用:

代码语言:javascript
复制
$(".arrow").click(function() {
    $(this).next().next().slideToggle();
});

但当我这样做时就不会了:

代码语言:javascript
复制
$(".arrow").click(function() {
    $(this).next('.box').slideToggle();
});

是什么原因导致第二种选择不起作用?我已经做了好几天了,都他妈的想不出来!非常感谢您的意见!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-17 05:57:23

The Problem

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

以下是.next()的医生说的话:

描述:获取匹配元素集合中每个元素紧跟其后的同级元素。如果提供了选择器,则仅当与该选择器匹配时才检索下一个同级。

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

使用.nextAll()的解决方案

如果您想要匹配选择器的下一个同级,您可以使用以下命令:

代码语言:javascript
复制
$(this).nextAll(".box").eq(0).slideToggle();

这将查找与选择器匹配的所有同级,然后只提取第一个同级。

创建您自己的.findNext()方法

我经常想知道为什么jQuery没有一个方法来解决这个问题,所以我自己做了一个:

代码语言:javascript
复制
// 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);
}

然后,您只需使用:

代码语言:javascript
复制
$(this).findNext(".box").slideToggle();

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

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

代码语言:javascript
复制
<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>

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

代码语言:javascript
复制
$(".arrow").click(function() {
    $(this).closest(".container").find(".box").slideToggle();
});

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

票数 50
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30281166

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档