我有一个页面,比如说5个帖子,都在#article
中。以下是用于切换隐藏/显示的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个帖子都会展开。
如何修改我的代码以仅展开该特定帖子?
发布于 2013-06-21 07:13:56
更改此行
$(".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');
});
发布于 2013-06-21 07:16:00
您需要在同一个article
div中找到一个div,而不是找到任何带有类div的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)
查找具有article
类的最接近的父类:
$(this).closest('.article')
然后查找该article
div的任何具有content
类的子类:
$(this).closest('.article').find('.content')
https://stackoverflow.com/questions/17225359
复制相似问题