以下 Jquery 允许单击“加载更多”按钮来显示帖子的更多评论。它仅适用于 1 个帖子及其评论。 如果我想循环遍历一组帖子及其评论,然后将此代码应用于评论以在单击按钮时加载更多评论,则这将无法正常工作,因为所有帖子都会循环相同的类/ID。 如何做到这一点?
$('.post').slice(0,5).show();
$('#btnMore').on('click', function() {
$('.post:hidden').slice(0,3).slideDown();
if($('.post:hidden').length === 0) {
$('#btnMore').fadeOut();
}
});
添加了 HTML:
@foreach($topans as $topanswer)
{{$topanswer->body}}
<div class="content">
@foreach($topanswer->comments as $topanscom)
<div class="post">
<p>{{$topanscom->comment}} </p>
</div>
@endforeach
<div class="btnHolder">
<button id="btnMore">Load More</button>
</div>
</div>
@endforeach
CSS:
.post {
display: none;
}
最佳答案
无论您生成此 html 的方式如何,您都需要创建一个容器来进行迭代,以便区分不同的集合。您还需要为按钮使用类而不是 id。
请注意 div 的“postSet”容器的引入,以及在迭代内部使用 this
来保持当前目标的范围。虽然您将使用不同的名称和样式,但此处显示的结构应该可以轻松适应您当前的实现。
// Iterate the containers for the initial showing
$('.postSet').each(function(){
// Use `this` in order to reference the current post set container
$('.post',this).slice(0,5).show();
});
$('.btnMore').on('click', function() {
// Locate the current container for the post set
var container = $(this).closest('.postSet');
// Use the post set container as a reference for scope
$('.post:hidden',container).slice(0,3).slideDown();
if($('.post:hidden',container).length === 0) {
$(this).fadeOut();
}
});
.postSet{
padding: 1% 3%;
border: 1px solid black;
}
.post{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="postSet">
<div class="post">Lorem ipsum</div>
<div class="post">Lorem ipsum</div>
<div class="post">Lorem ipsum</div>
<div class="post">Lorem ipsum</div>
<div class="post">Lorem ipsum</div>
<div class="post">Lorem ipsum</div>
<p><button class="btnMore" type="button">More</button></p>
</div>
<div class="postSet">
<div class="post">Lorem ipsum</div>
<div class="post">Lorem ipsum</div>
<div class="post">Lorem ipsum</div>
<div class="post">Lorem ipsum</div>
<div class="post">Lorem ipsum</div>
<div class="post">Lorem ipsum</div>
<p><button class="btnMore" type="button">More</button></p>
</div>
<div class="postSet">
<div class="post">Lorem ipsum</div>
<div class="post">Lorem ipsum</div>
<div class="post">Lorem ipsum</div>
<div class="post">Lorem ipsum</div>
<div class="post">Lorem ipsum</div>
<div class="post">Lorem ipsum</div>
<p><button class="btnMore" type="button">More</button></p>
</div>
关于jquery - 使用Jquery显示更多数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59673216/