显示一个隐藏和显示部分一次使用jquery
我试图显示和隐藏网页的某些部分,而不显示或隐藏其他具有类似名称的元素,例如我想能够显示某些评论回复而不会显示具有相同类名的其他评论回复。但我似乎不能让我的jquery工作正确。换句话说,我想单击类view-comments
中的一个元素,并显示类名最接近的部分more-comments
显示一个隐藏和显示部分一次使用jquery
这是我简化的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');
});
});
要做到这一点,我会做一切不具有默认隐藏的类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>
请问什么e.preventDefault();是什么,如果我删除它实际上做了什么?谢谢。 – gchow
您的'view-comments'元素是链接,默认情况下,链接导航到存储在'href'属性中的地址。当你舔这样的链接时,它会在绑定的jQuery函数被调用之前(或者至少在查看结果之前)导航到它的href中的页面。 'e.preventDefault();'防止发生这种情况 – DelightedD0D
请注意,这里假设您只希望一个部分一次可见(通常需要),但是如果您希望能够同时打开多个部分,使用@ Pekka的回答 – DelightedD0D
$('.view-comments').click(function (e) {
e.preventDefault();
$(this).closest('article').find('.more-comments').toggle();
});
尝试这种方式
个人而言,我更喜欢'$(this).closest('article')。find('。more-comments')。toggle();'因为它不太可能打破' html结构。但是+1 :) – DelightedD0D
请致电@ DelightedD0D包括回答为更新。或者如果你想我可以为你做。谢谢你的建议 – guradio
尝试http://jsfiddle.net/a8zbuj80/1这是你想要的 – guradio