我正在尝试显示和隐藏网页的某些部分而不显示或隐藏具有相似名称的其他元素例如我希望能够显示某些评论回复而不显示其他具有相同类名的评论回复.但我似乎无法让我的 jquery 正常工作。换句话说,我想单击带有 view-comments
类的 a 元素,并显示带有 more-comments
这是我简化的 HTML 代码。
HTML
<article>
<div>
<div>
....
<a class="view-comments" title="" href="">View Comments</a>
</div>
</div>
<section class="more-comments">
.......
</section>
</article>
<article>
<div>
<div>
....
<a class="view-comments" title="" href="">View Comments</a>
</div>
</div>
<section class="more-comments">
.......
</section>
</article>
<article>
<div>
<div>
....
<a class="view-comments" title="" href="">View Comments</a>
</div>
</div>
<section class="more-comments">
.......
</section>
</article>
<article>
<div>
<div>
....
<a class="view-comments" title="" href="">View Comments</a>
</div>
</div>
<section class="more-comments">
.......
</section>
</article>
查询
$(document).ready(function() {
$('.view-comments').click(function() {
$('.more-comments').toggle($(this).hasClass('view-comments'));
$(this).toggleClass('view-comments hide-comments');
});
});
最佳答案
为此,我将默认隐藏所有不具有 active
类的元素。然后,当您单击链接时(调用 prevent default 以停止页面导航),从所有 more-comments
部分中删除类 active
,然后添加类 active
到最近的 more-comments
部分
$(document).ready(function() {
$('.view-comments').click(function(e) {
e.preventDefault();
$('.more-comments').removeClass('active');
$(this).closest('article').find('.more-comments').addClass('active');
});
});
.more-comments:not(.active){
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article>
<div>
<div>
....
<a class="view-comments " title="" href="">View Comments</a>
</div>
</div>
<section class="more-comments active">
.......more-comments 1
</section>
</article>
<article>
<div>
<div>
....
<a class="view-comments" title="" href="">View Comments</a>
</div>
</div>
<section class="more-comments">
....... more-comments 2
</section>
</article>
<article>
<div>
<div>
....
<a class="view-comments" title="" href="">View Comments</a>
</div>
</div>
<section class="more-comments">
....... more-comments 3
</section>
</article>
<article>
<div>
<div>
....
<a class="view-comments" title="" href="">View Comments</a>
</div>
</div>
<section class="more-comments">
....... more-comments 4
</section>
</article>
关于jquery - 使用 Jquery 一次显示一个隐藏和显示部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33490662/