jQuery 具有嵌套可排序项的动态可排序项

jQuery dynamic sortables with nested sortable items

动态排序

Codepen Version

描述


我对动态可排序列表有疑问,哪些元素也应该是可排序的。 问题是,列表中的每个元素都是动态的,因为它将从模板 div 中克隆并附加到文档中。

问题


目前块 (.pb-row) 可以按预期排序。
但是动态添加的小部件的嵌套排序 (.builder-row-content) 不起作用。

只有第一个块中的嵌套节点是可拖动的,而且有很多错误。 我也可以将它们拖到行外。

额外添加的块中的节点根本不可拖动。

我也在控制台中收到此消息

无法在初始化之前调用 sortable 上的方法;试图调用方法 'refresh'

代码


Html 到 运行 可排序:

 <div class="pb-rows"> // Wrapper of all Blocks
   <div class="pb-row" name="pb-row"> // each Block
      <div class="builder-row-header">
          <span class="row-btn pb-handle fas fa-sort"></span>
           <div>Block</div>
           <span onclick="handleRemoveClick(this)" class="row-btn row-btn-right pb-remove fas fa-trash"></span>
       </div>
       <div class="pb-container">
          <div class="builder-row-content">
            // nested sortable widgets will appear here
          </div>
       </div>
   </div>
   // more .pb-rows will appear here
 </div>

尝试 jQuery 可排序列表:

// jQuery Sorting Lib
jQuery(".pb-rows").sortable({
  handle: ".pb-handle",
  cursor: "grabbing",
});

// jQuery Sorting Lib
jQuery(".builder-row-content").sortable({
  connectWith: '.pb-rows
  handle: ".pb-handle-widget",
  cursor: "grabbing",
});

尝试的解决方案无效:

const handleAddClick = e => {
  e.preventDefault();
  ...
  jQuery(".builder-row-content").sortable("refresh");
};

截图


Screenshot of implementation

您需要将 sortable 重新初始化到动态添加的元素上,因此:

将您的可排序事件包装在一个函数中

// Sorting
function enableSort() {
  // jQuery Sorting Lib
  $(".pb-rows").sortable({
    handle: ".pb-handle",
    cursor: "grabbing"
  });

  // jQuery Sorting Lib
  $(".builder-row-content").sortable({
    handle: ".pb-handle-widget",
    cursor: "grabbing"
  });
} enableSort();

然后调用pbCreateNode中的函数。

const pbCreateNode = (type, props, html) => {
  enableSort();
  let element = document.createElement(type);
  props &&
    props.forEach(prop => {
      let key = Object.keys(prop)[0];
      let value = prop[key];
      element.setAttribute(key, value);
    });
  html && (element.innerHTML = html);
  return element;
};