如何使用jquery sortable保存表格行的顺序而不使用" .toArray()"或" .serialize()"?

时间:2016-03-31 19:23:36

标签: jquery traversal jquery-ui-sortable dom-traversal jquery-traversing

让我们说我有一个使用jquery可排序的表。如何在拖动时获取行的innerHTML以与另一行的innerHTML交换,然后在不使用" .toArray()"或" .serialize()"。例如,我设法保存订单而不使用" .toArray()"或" .serialize()"通过使用向上和向下按钮来输出innerHTML。

    jQuery(function() {
    var ids = [];
    $("tbody#sortable").sortable({
        axis: "y",
        items: ".row_order", 
        forcePlaceholderSize: true,
        placeholder: "must-have-class",
    start: function(event, ui) {
      //Empty the array to avoid duplication.
      ids = [];
      //Store the ids in the array.
      $.each(event.target.children, function() {
            ids.push($(this).attr('id'));
      });
    },
    update: function(event, ui) {
      //Store the html in local variables
      var prevHtml = ui.item.prev().html();
      var nextHtml = ui.item.next().html();

      //Call .html and pass the html content as an argument
      ui.item.prev().html(nextHtml);
      ui.item.next().html(prevHtml);

      //On an update, loop through the sortable items and reset their items.
      for (var i = 0; i < event.target.children.length; i++) {
        $(event.target.children[i]).attr('id', ids[i]);
      }
    }        
    });
});

这是Fiddle

1 个答案:

答案 0 :(得分:2)

您的示例不起作用,因为您将项目的html内容分配给变量,而您没有以任何方式操纵DOM元素。

为了更新内部html,你必须在每个元素上调用.html()并传递html作为参数:

jQuery(function() {
  var ids = [];
  jQuery("#sortable_available").sortable({
    items: "li",
    start: function(event, ui) {
      //Empty the array to avoid duplication.
      ids = [];
      //Store the ids in the array.
      $.each(event.target.children, function() {
        ids.push($(this).attr('id'));
      })
    },
    update: function(event, ui) {
      //Store the html in local variables
      var prevHtml = ui.item.prev().html();
      var nextHtml = ui.item.next().html();

      //Call .html and pass the html content as an argument
      ui.item.prev().html(nextHtml);
      ui.item.next().html(prevHtml);

      //On an update, loop through the sortable items and reset their items.
      for (var i = 0; i < event.target.children.length; i++) {
        $(event.target.children[i]).attr('id', ids[i]);
      }
    }
  });
});

可能有更好的方法来维护ID,但上面是如何实现您的需求的一个粗略示例。

点击 here 进行实时演示。