Sortable with dynamic content

谁说胖子不能爱 提交于 2021-02-05 10:49:07

问题


So I use jQuery UI sortable plugin to sort photos in a small gallery.

$(function() {
  $("#area").sortable({
    items: '.sort-wrapper',
    cursor: "move",
    handle: ".photo-handler",
    opacity: 0.5,
    scroll: true,
    scrollSensitivity: 100,
    scrollSpeed: 5,
    revert: 100,
    tolerance: "pointer",
    update : function () {
      var order = $('#area').sortable('serialize');
      $.ajax({
      type : 'POST',
      url : '/file.php',
      data : order
    });
  }
}).disableSelection();

On the same page I dynamically add and remove photos. PHP script returns HTML code with div's with image links and buttons "remove" and "move" (sortable handler).

Example:

<div class="sort-wrapper">
  <a href="photo001.jpg"><img src="photo001m.jpg" alt=""></a>
  <button type="button" class="remove-this-photo">Remove</button>
  <button type="button" class="photo-handler">Move</button>
</div>

The problem is sortable stops working when I add new files or remove a file(s) from #area. I've been looking for solution, have found sortable('refresh') method, but it's not working for me.

The script which adds new photos in the #area is quite standard. I use $.ajax({}) and .done, .fail, .always methods. I managed to use sortable('destroy') method when starting uploading new files and do something like this after uploading is finished:

.always(function() {
  $("#area").sortable();
});

The code above makes the #area sortable again, but I must copy all the settings again to configure it my way. How to bind sortable to make it work after dynamic content is loaded or how to store all the settings outside sortable() and be able to use it again on the same page?


回答1:


If you add new content to the sortable element you'll need to refresh the initialised instance. To do that, call the refresh option, like this:

.always(function() {
  $("#area").sortable('refresh');
});


来源:https://stackoverflow.com/questions/46951559/sortable-with-dynamic-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!