jquery - 在jquery上方加载旧评论后将固定评论重新定位在顶部
问题描述
我有这种评论安排,默认情况下,固定评论显示在顶部。
<button>Show All Comments</button>
<ul class="comments">
<!--Ajax loaded hidden posts-->
<li class="fixed">Fixed Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
</ul>
当我单击“按钮”时,它会在顶部加载过去的评论,并且fixed
帖子会从列表中移出..
问题
.fixed
使用 Jquery,单击按钮后,如何再次将此评论重新定位到顶部?
$(document).on("click","button",function(){
//Show Ajax loaded hidden posts code
$(".comments").prepend("<li>Old Comment</li><li>Old Comment</li><li>Old Comment</li><li>Old Comment</li><li>Old Comment</li><li>Old Comment</li>")
//requested code
/* $(".comments").find(".fixed").append to new top?*/
})
.fixed{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<button>Show All Comments</button>
<ul class="comments">
<!--Ajax loaded hidden posts-->
<li class="fixed">Fixed Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
</ul>
解决方案
由于(正如您所指出的)可能存在也可能不存在评论,因此我们不能通过在第一条.fixed
评论之后插入新评论来作弊。.fixed
取而代之的是,按照您的操作添加新注释,然后将固定注释添加到同一节点上(这将自动将它们从 DOM 树中的原始位置删除。)这适用于任意数量的.fixed
元素(包括零) .
$(document).on("click", "button", function() {
// add new elements:
$(".comments").prepend("<li>Old Comment</li><li>Old Comment</li><li>Old Comment</li><li>Old Comment</li><li>Old Comment</li><li>Old Comment</li>")
// rearrange the .fixed elements back to the top:
$(".fixed").prependTo($('.comments'))
})
.fixed {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<button>Show All Comments</button>
<ul class="comments">
<li class="fixed">Fixed Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
<li>Comment</li>
</ul>
推荐阅读
- angular - 拦截处理http错误导致问题
- eclipse - Eclipse,Buildship,拼图:java.lang.module.FindException
- html - 如果 div 存在且具有值,如何显示或隐藏 div
- javascript - Firefox 扩展的后台脚本可以向页面上下文中的 blob url 发出跨源请求吗?
- python-3.x - 插入excel表作为输入
- django - 获取保存在 django bulk_create 中的记录总数
- reactjs - 创建新的反应应用程序时如何停止权限
- python - Django:更新帖子后,我怎样才能使“更新”成功消息暂时,直到我刷新页面。因为现在刷新后它仍然存在
- github - 通过 Github 发布网站时出现“找不到页面”错误
- python - 带有用户输入的 FizzBuzz 类型游戏 - 整数错误