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

标签 javascript jquery jquery-ui jquery-ui-sortable

我正在使用 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

最佳答案

您可以使用一个 refreshPositions() 函数来返回表示可排序项的对象。然后,您可以通过调用该对象上的 .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

关于javascript - 如何获得 jQuery 可排序列表顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39182974/

相关文章:

javascript - 如何在JQuery 中只获取无序列表菜单中的第一个列表元素?

javascript - Jquery resizing() 显示调整大小图标但不调整大小

Javascript : add/remove json element in json object

javascript - Jquery ui 可调整高度 - 默认高度 :0px

javascript - Vue,获取选择选项的值和名称

javascript - PHP 和 javascript 组合变量问题

php - Access 数据库并向多用户 Web 界面报告

javascript - 多个动态 Canvas 元素?

JavaScript 循环输入创建一个对象数组

jquery - 谷歌浏览器选项,如滑动面板