如何获得 jQuery 可排序的列表顺序?

How to get jQuery sortable list order?

我正在使用 jQuery Sortable 以允许用户在页面上拖放元素。当用户拖动 div 时,我需要获取列表的更新顺序并将其传递给后端。到目前为止我已经尝试过:

  $( function() {
    $( "#sortable" ).sortable({
        axis: 'y',
        stop: function (event, ui) {
            var data = $(this).sortable('serialize');
            alert(data);
            $.ajax({
                    data: oData,
                type: 'POST',
                url: '/url/here'
            });
    }
    });
    $( "#sortable" ).disableSelection();
  } );

但这使得动画真的不流畅并且没有数据提示。每次用户拖放 div?

时,如何获取位置列表

JSFIDDLE

相反,请使用 toArray() 方法,详见此处:http://api.jqueryui.com/sortable/#method-toArray

有一个 refreshPositions() 函数,您可以使用它 returns 表示可排序项目的对象。然后,您可以通过对该对象调用 .children() 来获取更新后的子列表。

将位置保存到stop事件中的变量,该事件在您完成排序后触发。

我已经更新了您的函数以包含 stop 事件:

$("#sortable").sortable({
  stop: function(ev, ui) {
    //Get the updated positions by calling refreshPositions and then .children on the resulting object.
    var children = $('#sortable').sortable('refreshPositions').children();
    console.log('Positions: ');
    //Loopp through each item in the children array and print out the text.
    $.each(children, function() {
        console.log($(this).text().trim());
    });
  }
});

Updated Fiddle