【问题标题】:jQuery sortable doesn't work with dynamically added divsjQuery sortable 不适用于动态添加的 div
【发布时间】:2018-10-02 19:57:49
【问题描述】:

我创建了一个按钮,可以动态添加 divs 和里面的元素。我想使用 jQuery .sortable() 来更改 divs 的顺序,但由于某种原因它不正确。

我的代码:https://jsfiddle.net/t5o1npd4/

$(document).ready(function() {
  //Create button
  $(document).on('click', '#add', function() {
    var $skill1 = '<select><option disabled selected hidden>Select One</option></select>';

    $('<div class="myClass"></div>').appendTo('#area').append($skill1);
  });
});

//Why not works the sortable to dynamically added divs??
$("#area").sortable({
  appendTo: "parent",
  helper: "clone",
  handle: ".myClass",
  stop: function(ui, event) {
    var id = event.item.index();
  }
}).disableSelection();
.myClass {
  padding: 5px;
  padding-right: 10px;
  border: 1px solid #909090;
  border-bottom: none;
  background-color: #cccccc;
}

.myClass:last-child {
  border-bottom: 1px solid #909090;
}

#area input[type="text"] {
  display: none;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<button id="add"><b style="font-size:14px;">+</b> Add</button>

<div id="area"></div>

【问题讨论】:

    标签: jquery html jquery-ui-sortable


    【解决方案1】:

    尝试去掉初始化语句中的句柄行。

    $(document).ready(function() {
      //Create button
      $(document).on('click', '#add', function() {
        var $skill1 = '<select><option disabled selected hidden>Select One</option></select>';
    
        $('<div class="myClass"></div>').appendTo('#area').append($skill1);
      });
    });
    
    //Why not works the sortable to dynamically added divs??
    $("#area").sortable({
      appendTo: "parent",
      helper: "clone",
      stop: function(ui, event) {
        var id = event.item.index();
      }
    }).disableSelection();
    .myClass {
      padding: 5px;
      padding-right: 10px;
      border: 1px solid #909090;
      border-bottom: none;
      background-color: #cccccc;
    }
    
    .myClass:last-child {
      border-bottom: 1px solid #909090;
    }
    
    #area input[type="text"] {
      display: none;
    }
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    
    <button id="add"><b style="font-size:14px;">+</b> Add</button>
    
    <div id="area"></div>

    【讨论】:

      猜你喜欢
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      • 2012-01-12
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多