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

在多个div中使用jquery显示/隐藏内容,jquery,html,css,Jquery,Html,Css,我有一个单独的页面,比如说5篇文章,都在#文章中。以下是用于切换隐藏/显示的jQuery代码: $(".click-show-more").click(function () { if($(".content").hasClass("show-more")) { $(this).text("(Show Less)"); } else { $(this).text("(Show More)"); } $(".content").tog

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

$(".click-show-more").click(function () {
    if($(".content").hasClass("show-more")) {
        $(this).text("(Show Less)");
    } else {
        $(this).text("(Show More)");
    }
    $(".content").toggleClass("show-more");
});
HTML
结构是:

<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次,每当我点击
showmore
,所有5-6篇文章都会展开

如何修改代码以仅扩展该特定帖子?

更改此行

$(".content").hasClass("show-more")
$(".content").toggleClass("show-more");

您的点击只会影响特定文章的
内容
。因此,利用
这个
上下文对您有利

还有这条线

$(".content").hasClass("show-more")
$(".content").toggleClass("show-more");
应该是

$(this).closest('.article').find('.content').toggle();
除非已定义
.show more{display:none}

代码

$(".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');
});

您需要在同一篇
文章中找到一个div,而不是查找任何包含class
内容的div

所以它看起来像这样:

$(".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:

$(this)
查找具有
文章
类的最近父级:

$(this).closest('.article')
$(this).closest('.article').find('.content')
然后查找该
文章
div中具有
内容
类的任何子级:

$(this).closest('.article')
$(this).closest('.article').find('.content')

那是因为你还需要将切换切换切换到正确的div。效果非常好!谢谢。@PalakArora。。很高兴能帮忙:)