【问题标题】:jQuery dynamic sortables with nested sortable items带有嵌套可排序项的 jQuery 动态可排序
【发布时间】:2019-10-30 18:48:22
【问题描述】:

动态排序

Codepen Version

说明


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

问题


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

只有第一个块中的嵌套节点是可拖动的并且非常有问题。 我也可以将它们拖到行外。

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

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

无法在初始化之前调用 sortable 上的方法;试图调用方法“刷新”

代码


运行排序的 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

【问题讨论】:

  • 一个可运行的例子会很好。因为这是一个非常具体的问题。
  • 好的,我会为此设置一个 github repo :)
  • A codesandbox.io 可能会更好,因为我们可以在浏览器中运行它:)
  • 我为它创建了一个codepen版本:codepen.io/pbahr/pen/VJaRay

标签: javascript php jquery html jquery-ui-sortable


【解决方案1】:

您需要重新初始化可排序到动态添加的元素,所以:

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

// 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;
};

【讨论】:

    猜你喜欢
    • 2016-05-15
    • 1970-01-01
    • 2011-02-18
    • 2012-06-01
    • 1970-01-01
    • 2019-10-11
    • 2012-11-06
    • 2010-10-31
    • 1970-01-01
    相关资源
    最近更新 更多