【问题标题】:How to get jQuery sortable list order?如何获取 jQuery 可排序列表顺序?
【发布时间】:2016-08-27 15:52:19
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    您可以使用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

    【讨论】:

      【解决方案2】:

      改为使用toArray() 方法,在此处详述:http://api.jqueryui.com/sortable/#method-toArray

      【讨论】:

      • 感谢@Sterling 的回答。试过还是同样的问题:jsfiddle.net/kevinabraham/7rbv20yd/1
      • 在您的小提琴中,您需要在可排序对象上调用 toArray 方法,因此 $( "#sortable" ).sortable("toArray") 此外,正在排序的项目,即 lis 没有 ID。为了使用toArray,可排序的直接子级需要有 id
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-14
      • 2015-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      相关资源
      最近更新 更多