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

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

假设我有一个使用 jquery 可排序的表。如何在拖动时让一行的innerHTML与另一行的innerHTML交换,然后在提交时保存订单而不使用“.toArray()”或“.serialize()”。例如,我成功地通过使用向上和向下按钮交换innerHTML来保存订单,而无需使用“.toArray()”或“.serialize()”。

    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

最佳答案

您的示例将不起作用,因为您将项目的 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]);
      }
    }
  });
});

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

点击here 进行现场演示。

关于jquery - 如何使用 jquery sortable 保存表行的顺序而不使用 ".toArray()"或 ".serialize()"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36341973/

相关文章:

javascript - 即使以 Json 格式发送数据后,莫里斯图也无法处理动态数据

javascript - 在点击 td 后尝试获取 td 行文本

node.js - 卡住了,完整性,用nodejs重复列出目录中的所有文件?

javascript - 排序后将子部分添加到正确的父部分 - Angular JS

jquery-ui - jQuery UI 可按固定行排序

jquery - Safari Mobile 中的 JavaScript 卸载事件?

javascript - 更新 Stripe 客户地址而非卡信息

php - JQuery-Tabledit 一次只更新一列(我的代码有什么问题)

prolog - 如何处理 Prolog 图形遍历中的路径

javascript - JQuery UI 可排序 - 可以取消特定元素吗?