如何使插入的项目可排序

how to make inserted items sortable

$('.parent').sortable({
 containment: "parent",
 tolerance: "pointer",
 axis: "x"
 });
 
 $('button').on('click', function(){
 var str = $('#store').html();
 $(str).insertBefore($('.parent').eq(0));
 });
.parent{
background:silver;
margin:9px 0;
}
.title{
background:gold;
display:inline-block;
width:25%;
cursor:cell;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id='store'>
<div class='parent'>
<div class='title'>lorem</div>
<div class='title'>ipsum</div>
</div>
</div>
<br>
<button>CLICK</button>

如何使插入的项目可排序?

我尝试了所有解决方案 here and here 并且...

没有任何效果。

添加项目时,需要运行 refresh:

Refresh the sortable items. Triggers the reloading of all sortable items, causing new items to be recognized.

关于展示位置,您的选择似乎超出了您的需要。我怀疑您只需要将更多项目插入同一列表即可。考虑以下因素:

$(function() {
  $('.parent').sortable({
    containment: "parent",
    tolerance: "pointer",
    axis: "x"
  });

  $('button').on('click', function() {
    var str = $('#store .parent').html();
    $(str).insertBefore($('.parent div:eq(0)'));
    $('.parent').sortable("refresh");
  });
});
.parent {
  background: silver;
  margin: 9px 0;
}

.title {
  background: gold;
  display: inline-block;
  width: auto;
  cursor: cell;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id='store'>
  <div class='parent'>
    <div class='title'>lorem</div>
    <div class='title'>ipsum</div>
  </div>
</div>
<br>
<button>CLICK</button>

如果您需要一个新的列表,那么您需要添加它并重新分配 sortable 给新的项目。

$(function() {
  $('.parent').sortable({
    containment: "parent",
    tolerance: "pointer",
    axis: "x"
  });

  $('button').on('click', function() {
    var str = $('#store .parent:last').prop("outerHTML");
    $(str).insertBefore($('.parent:eq(0)'));
    $("#store .parent").sortable({
      containment: "parent",
      tolerance: "pointer",
      axis: "x"
    });
  });
});
.parent {
  background: silver;
  margin: 9px 0;
}

.title {
  background: gold;
  display: inline-block;
  width: 25%;
  cursor: cell;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id='store'>
  <div class='parent'>
    <div class='title'>lorem</div>
    <div class='title'>ipsum</div>
  </div>
</div>
<br>
<button>CLICK</button>

希望对您有所帮助。