2013-06-20 54 views
0

我有一个单页,有5个帖子,全部在#article。以下是jQuery代码用来切换隐藏/显示:在多个DIV中使用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次,每当我点击Show More,所有5-6个帖子都展开。

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

回答

1

改变这一行

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

$(this).closest('.article').find('.content').hasClass("show-more") 

你点击只会影响特定物品的content。因此,使用this上下文对您有利。

而且这条线

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

Check Fiddle

+0

没有用。仍然是同样的事情。 –

+0

这是因为您需要将切换更改为正确的div。 – jcsanyi

+0

@PalakArora ..检查编辑 –

0

而是找到任何分度content类的,你需要找到相同的article专区内的一个。

因此,这将是这个样子:

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

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

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

然后找到那个的孩子div有content分类:

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