首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在多个DIVs中使用jquery显示/隐藏内容

在多个DIVs中使用jquery显示/隐藏内容
EN

Stack Overflow用户
提问于 2013-06-21 07:12:40
回答 2查看 1.5K关注 0票数 0

我有一个页面,比如说5个帖子,都在#article中。以下是用于切换隐藏/显示的jQuery代码:

代码语言:javascript
运行
复制
$(".click-show-more").click(function () {
    if($(".content").hasClass("show-more")) {
        $(this).text("(Show Less)");
    } else {
        $(this).text("(Show More)");
    }
    $(".content").toggleClass("show-more");
});

HTML结构是:

代码语言:javascript
运行
复制
<div class="article">
    <div class="content show-more">Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. 

Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here. Some text here.
    </div>
    <div class="click-show-more">(Show More)</div>
</div>

现在,我有了上面的结构,在一个页面上有5-6次,每当我点击Show More时,所有5-6个帖子都会展开。

如何修改我的代码以仅展开该特定帖子?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-06-21 07:13:56

更改此行

代码语言:javascript
运行
复制
$(".content").hasClass("show-more")

代码语言:javascript
运行
复制
$(this).closest('.article').find('.content').hasClass("show-more")

您的点击应该只影响特定文章的content。因此,使用this上下文对您有利。

还有这一行

代码语言:javascript
运行
复制
$(".content").toggleClass("show-more");

应该是

代码语言:javascript
运行
复制
$(this).closest('.article').find('.content').toggle();

除非已经定义了.show-more { display: none }

代码

代码语言:javascript
运行
复制
$(".click-show-more").click(function () {
    var $closestContent = $(this).closest('.article').find('.content');

    if($closestContent.hasClass("show-more")) {
        $(this).text("(Show Less)");
    } else {
        $(this).text("(Show More)");
    }
    $closestContent.toggleClass('show-more');
});
票数 1
EN

Stack Overflow用户

发布于 2013-06-21 07:16:00

您需要在同一个article div中找到一个div,而不是找到任何带有类div的div。

所以它看起来像这样:

代码语言:javascript
运行
复制
$(".click-show-more").click(function () {
    var content = $(this).closest('.article').find('.content');
    if(content.hasClass("show-more")) {
        $(this).text("(Show Less)");
    } else {
        $(this).text("(Show More)");
    }
    content.toggleClass("show-more");
});

实际发生的是,我们使用的是被点击的div:

代码语言:javascript
运行
复制
$(this)

查找具有article类的最接近的父类:

代码语言:javascript
运行
复制
$(this).closest('.article')

然后查找该article div的任何具有content类的子类:

代码语言:javascript
运行
复制
$(this).closest('.article').find('.content')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17225359

复制
相关文章

相似问题

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