首页 > 解决方案 > 在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>

标签: jquery

解决方案


由于(正如您所指出的)可能存在也可能不存在评论,因此我们不能通过在第一条.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>


推荐阅读