拖动多个项目时 jQuery 索引返回 -1

问题描述 投票:0回答:1

我有两个表,我可以使用可排序拖放多个元素。我的问题是,当我从 table2 中拖动项目有时在 table1 中时,ui.item.index() 返回 -1。

经过一些测试,我发现问题在于拖动的初始位置。如果我开始拖动 table2 索引 0,一切都会正常。 see image

但是如果我开始从任何其他位置(例如 2)拖动, ui.item.index() 返回 -1 enter image description here

这是一个棘手的问题,我无法在测试环境中重现它。如果有帮助的话,我在下面留下部分代码:

$("#table1 tbody").sortable({
    connectWith: "#table2 tbody",
    helper: function (e, item) {
      const $helper = $("<div/>");
      const $originals = item.children();

      // Select the row that user is moving
      table1Api.row(item).select();

      const data = item.parent().children(":has(input:checked)").clone();
      matchHelperSizeToOriginal(data, $originals);

      // Hide siblings with checked inputs & storing the data
      item.data("data", data).siblings(":has(input:checked)").hide();

      return $helper.append(data);
    },
    start: function (e, ui) {
      const data = ui.item.data("data");
      ui.helper.append(data);
      // Remove each dragged row
      // irrelevant code here

    },
    stop: function (e, ui) {
      // irrelevant code here
    },
    receive: function (e, ui) {
      const nodes = ui.item.data("data");
      let newIndex = ui.item.index(); // returns -1
      console.log(newIndex);
    },
    remove: function (e, ui) {
      // irrelevant code here
    },
    axis: "xy",
    cursor: "grabbing",
  });
$("#table2 tbody").sortable({
    connectWith: "#table1 tbody",
    items: "tr:not(:has(.dataTables_empty))",
    helper: function (e, item) {
      const $helper = $("<div/>");
      const $originals = item.children();

      // Select the row that user is moving
      table2Api.row(item).select();

      const data = item.parent().children(":has(input:checked)").clone();
      matchHelperSizeToOriginal(data, $originals);

      // Hide siblings with checked inputs & storing the data
      item.data("data", data).siblings(":has(input:checked)").hide();

      return $helper.append(data);
    },
    start: function (e, ui) {
      const data = ui.item.data("data");
      ui.helper.append(data);
    },
    stop: function (e, ui) {
      ui.item.siblings(":hidden").show();
    },
    receive: function (e, ui) {
      // irrelevant code here
    },
    remove: function (e, ui) {
      // irrelevant code here
    },
    axis: "xy",
    cursor: "grabbing",
  });
javascript jquery jquery-ui-sortable
1个回答
0
投票

我刚刚发现了问题。在 table2 的删除事件中,我从 table2 中删除数据并更新循环内的显示。

remove: function (e, ui) {
   const data = ui.item.data("data");
   for (const d of data) {
     table2.row(d).remove().draw();
   }
},

将表格移出循环即可解决问题。

remove: function (e, ui) {
   const data = ui.item.data("data");
   for (const d of data) {
     table2.row(d).remove();
   }
   table2.rows().draw()
},
© www.soinside.com 2019 - 2024. All rights reserved.