我试图在不显示或隐藏其他具有相似名称的元素的情况下显示和隐藏网页的某些部分,例如,我希望能够显示某个评论回复,而不会显示另一个具有相同类名的评论回复。但是我似乎不能让我的jquery正常工作。换句话说,我想要单击包含类view-comments
的元素,并显示包含带有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>
Jquery
$(document).ready(function() {
$('.view-comments').click(function() {
$('.more-comments').toggle($(this).hasClass('view-comments'));
$(this).toggleClass('view-comments hide-comments');
});
});
发布于 2015-11-03 11:08:16
要做到这一点,我将使所有默认情况下不隐藏类active
的元素。然后,当您单击一个链接(调用阻止默认以停止页面导航)时,从所有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>
发布于 2015-11-03 11:10:10
$('.view-comments').click(function (e) {
e.preventDefault();
$(this).closest('article').find('.more-comments').toggle();
});
试试这条路
https://stackoverflow.com/questions/33490662
复制相似问题