jQuery UI Sortable,如何确定更新事件中的当前位置和新位置?

Ami*_*mir 43 jquery-ui jquery-ui-sortable

我有:

<ul id="sortableList">
     <li>item 1</li>
     <li>item 2</li>
     <li>item 3</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

我已连接到update: function(event, ui) { }但不知道如何获得元素的原始和新位置.如果我将项目3移动到项目1之上,我希望原始位置为2(基于0的索引)并且项目3的新位置为0.

Rus*_*sby 90

$('#sortable').sortable({
    start: function(e, ui) {
        // creates a temporary attribute on the element with the old index
        $(this).attr('data-previndex', ui.item.index());
    },
    update: function(e, ui) {
        // gets the new and old index then removes the temporary attribute
        var newIndex = ui.item.index();
        var oldIndex = $(this).attr('data-previndex');
        $(this).removeAttr('data-previndex');
    }
});
Run Code Online (Sandbox Code Playgroud)


Ric*_*man 18

调用更新函数时,ui.item.sortable尚未更新,但UI元素已在视觉上移动.
这允许您在更新功能中获取旧位置和新位置.

   $('#sortable').sortable({    
        update: function(e, ui) {
            // ui.item.sortable is the model but it is not updated until after update
            var oldIndex = ui.item.sortable.index;

            // new Index because the ui.item is the node and the visual element has been reordered
            var newIndex = ui.item.index();
        }    
});
Run Code Online (Sandbox Code Playgroud)

  • 不适用于jQuery 1.7,jQuery UI 1.8 - 虽然这个解决方案听起来很有前途 (4认同)
  • 对我来说,`ui.item.sortable.index`和`ui.item.index()`都返回相同的整数.我开始使用`ui.item.sortable.dropindex`来获取新索引 (2认同)

Fra*_*kie 10

您有多种可能性来检查旧位置和新位置.我会把它们放到数组中.

$('#sortable').sortable({
    start: function(e, ui) {
        // puts the old positions into array before sorting
        var old_position = $(this).sortable('toArray');
    },
    update: function(event, ui) {
        // grabs the new positions now that we've finished sorting
        var new_position = $(this).sortable('toArray');
    }
});
Run Code Online (Sandbox Code Playgroud)

然后,您可以轻松提取所需内容.


小智 5

我一直在寻找同一问题的答案.根据Frankie的贡献,我能够获得开始和结束的"订单".我使用var有一个变量范围的问题,所以我只是将它们存储为.data()而不是本地变量:

$(this).data("old_position",$(this).sortable("toArray"))
Run Code Online (Sandbox Code Playgroud)

$(this).data("new_position",$(this).sortable("toArray"))
Run Code Online (Sandbox Code Playgroud)

现在你可以这样调用它(来自更新/结束函数):

console.log($(this).data("old_position"))
console.log($(this).data("new_position"))
Run Code Online (Sandbox Code Playgroud)

信用仍然归Frankie :)


Nic*_*nda 5

这对我有用

$('#sortable').sortable({
start: function(e, ui) {
    // puts the old positions into array before sorting
    var old_position = ui.item.index();
},
update: function(event, ui) {
    // grabs the new positions now that we've finished sorting
    var new_position = ui.item.index();
}
});
Run Code Online (Sandbox Code Playgroud)