jQueryUI 可排序目标元素 ID

jQueryUI sortable target element ID

我想创建一个uild 动态图片库工具并使用jquery-ui 可排序技术来拖动和drop/sort 它们。

我想按类别对它们进行分组。首先,我动态地 build 列表和 build 我连接的可排序 <ul>s。当我拖放图像时,序列化 ID 正在触发。我的 AJAX 调用向我的 PHP 发送了 2 个帖子,每个新的 id 数组。但我的问题是我需要组 ID,我将图像放到该组 ID 中。仅凭 id 不足以满足我的查询。例如:

$(document).ready(function(){
    $("#sortable0, #sortable1, #sortable2").sortable({
        connectWith: ".connectedSortable",
        placeholder: "ui-state-highlight",
        opacity: 0.6, 
        update: function() {
            var order = $(this).sortable("serialize", {key:"id"});        
                $.ajax({
                    type: "POST",
                    data: {order: order},                       
                    url: '/backend/ajax/sort_sc_img.php' 
                });   
            }
        });
    $("#sortable").disableSelection();
});
<div>
  <ul id ="sortable0" class="connectedSortable">
    <li id="1">
      <img src="image01.jpg">
    </li>
    <li id="2">
      <img src="image02.jpg">
    </li>
  </ul>
  
  <ul id ="sortable1" class="connectedSortable">
    <li id="1">
      <img src="image03.jpg">
    </li>
    <li id="2">
      <img src="image04.jpg">
    </li>
  </ul>
  
  <ul id ="sortable2" class="connectedSortable">
    <li id="1">
      <img src="image05.jpg">
    </li>
    <li id="2">
      <img src="image06.jpg">
    </li>
  </ul>
</div>

jQueryUI update function API 显示该函数使用 2 个参数 updateui 回调。 ui 对象有一个 sender 属性 即:

The sortable that the item comes from if moving from one sortable to another

因此,通过添加这些参数,您可以访问父级 <ul>,例如:

$("#sortable0, #sortable1, #sortable2").sortable({
    connectWith: ".connectedSortable",
    placeholder: "ui-state-highlight",
    opacity: 0.6,
    update: function (event, ui) {
        var order = $(this).sortable("serialize", {
            key: "id"
        });

        var group = ui.sender === null ? null : ui.sender[0].id; // get the parent <ul> id
        console.log('group', group, 'order', order); // just log for this demo
    }
});

此外,请注意 serialize 仅在属性值匹配预定义格式时才有效,默认情况下为 "setname_number" 因此列表项应具有 id,如 [=20] =].如果您不想使用默认值,jQueryUI API 允许您为格式指定不同的属性和正则表达式。

编辑:

在 jQueryUI receive 函数上添加一个钩子允许我们在放置项目时抓取接收目标组的 id

receive: function(event, ui) {
    var group = event.target.id;
    console.log('receiving group', group);

    // do something with the group
}

Updated demo