簡體   English   中英

通過拖放對數組重新排序

[英]Reorder an array with drag and drop

我有一個像這樣的數組:

tableObj =  [
  {
    label: 'here',
    value: 36,
    element: '$(the li that this info is about)',
    index: 0
  },
  {
    label: 'are',
    value: 42,
    element: '$(the li that this info is about)',
    index: 1
  },
  {
    label: 'some',
    value: 21,
    element: '$(the li that this info is about)',
    index: 2
  },
  {
    label: 'tags',
    value: 26,
    element: '$(the li that this info is about)',
    index: 3
  }
];

當我顯示數組的內容時,我這樣做:

$(".sortable-list").sortable({
  axis: "y",
  containment: ".sortable-list",
  revert: true,
  start: function(event, ui) { 
    var updt = ui.item.index();
    tableObj.value = updt;
  },
  update: function(event, ui) { 
    var updt = ui.item.index();
    tableObj.index = updt;
  }
});
$( "#sortable" ).disableSelection();

顯示為<li> ,在空的<ul class=".sortable-list"></ul>之間進行標記。 我想要做的是拖動<li>標記並對元素進行重新排序,然后通過單擊按鈕來捕獲數組的新狀態。 這意味着,如果我將第二個元素移到第一個位置,則當我單擊按鈕時,數組將在位置0的第二個元素中重新排序。我要使用上面的jQuery函數要做的就是設置一個新值,但是我無法捕獲重新排序的新數組。

有人可以幫我嗎? 先感謝您 ! :)

使用var newList=$(".sortable-list").sortable("toArray")

查看以下Codepen示例:

https://codepen.io/Sinetheta/pen/qvbCr?editors=1111

https://codepen.io/fraigo/pen/WawQBy

感謝亞歷山大·費多托夫! 他開車帶我走了正確的路! :)這是我的解決方案:

var manipulate, oldIndex;
$(".sortable-list").sortable({
     axis: "y",
     containment: ".sortable-list",
     revert: true,

     start: function(event, ui) { 
          var updt = ui.item.index();
          manip = updt;
          console.log("Start: " + manipulate);
          oldIndex = sortableList[manipulate];
     },

     update: function(event, ui) { 
          var newIndex = ui.item.index();
          console.log("End: " + newIndex);
          sortableList.splice(manipulate, 1);
          sortableList.splice(newIndex, 0, oldIndex);

          console.log(sortableList);
          }
   });

   $(".sortable-list").disableSelection();

每次添加<li>時,我都必須創建一個表。 然后,我發現誰是被拖放的人。 在“更新”函數中,我們從數組中刪除該項(以前保存到變量oldIndex ),然后將其添加到數組中的新索引中。 我希望這會對其他人有所幫助! :)

可能的解決方案:稍微修改標記,為每個li添加數據屬性,其中li包含tableObj數組中當前元素的標識符。

在更新函數中,獲取當前移動元素的標識符:

var id = $(event.toElement).data('id');

使用此標識符在tableObj數組中找到元素:

var obj = tableObj.find(function(o) { return o.id === id});

然后找到最近移動的對象的舊索引:

var oldIndex = tableObj.indexOf(obj);

獲取對象的新索引:

var newIndex = ui.item.index();

然后從舊位置刪除obj並在新索引處插入:

tableObj.slice(oldIndex, 1);
tableObj.slice(newIndex, 0, obj);

然后,您將獲得具有正確元素順序的數組(與視圖上的順序相同)。 如果您不需要即時重新排列數組-您可以創建原始數組的副本並在副本上進行修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM