2012-01-28 78 views
0

我已經成功實現了JQuery Sortable。我也可以使用單獨的調用將其寫入數據庫。但是,這僅適用於受影響的第一組匹配類。第二,如果有的話,我假設其後的,不工作。Jquery可排序對象Ajax請求發送錯誤的對象

<ul class="grouped-articles-list"> 
     <li id="4weight10"></li> 
     <li id="3weight20"></li> 
     <li id="2weight30"></li> 
</ul> 

<ul class="grouped-articles-list> 
     <li id="5weight50"></li> 
     <li id="6weight60"></li>  
     <li id="22weight70"></li> 
     <li id="18weight80"></li>  
</ul> 

我有多個UL共享一個共同的類。視覺方面都可以正確地完全排序。然後我寫對象到一個數組,Array = $(「。grouped-articles-list」)。sortable('toArray')然後調用一個ajax函數。如果我做trace/console.log,它只會返回前一個(1st)類的對象。

是否可以在多個場合使用Classes,並且仍然可以使用ToArray?在這種情況下,如果我影響第二個UL並做了一個跟蹤,它仍然會返回[「4weight10」,「3weight20」,「2weight30」]。

我會貼上我下面的代碼,但它是一個有點冗長......

function makeSortable(){ 
    var before; 
    var weight; 
    var newWeight = []; 
    var newID = []; 

    $(".grouped-articles-list").sortable({ 
     tolerance: 'pointer', 
     items: "li:not(.sortable_disabled)", 
     start: function(event, ui){ 
      newWeight.length = 0; 
      var resultbefore = $(".grouped-articles-list").sortable('toArray'); 
      before = resultbefore; 
      //goes through each item and saves their weight to an array 
      $.each(before, function(i) { 
      newWeight.push(splitWeightFromId(before[i])[3]);    
      }); 
     }, 
     stop: function(event, ui) { 
      newID.length = 0; 
      var after = $(".grouped-articles-list").sortable('toArray'); 
      $.each(after, function(i) { 
      //goes through each item in the array and saves out their id 
      newID.push(splitWeightFromId(after[i])[1]); 
      // Only adds changed items 
      if (newID[i] !== splitWeightFromId(before[i])[1]){ 
      //as the items move, but the weights stay the same 
      //sends the affected ID with the always stationary weight off 
       change_weight(newID[i], newWeight[i]) 
     }  
    }); 
}); 

的Ajax功能

function change_weight(link_id, new_weight) { 
    $.ajax({ 
     type: "PUT", 
     url: "/article_relationships/" + link_id, 
     data: {article_relationship : { 
            weight : new_weight 
            } }, 
     datatype: "js", 
     remote: "true" 
     }); 
} 

謝謝您的時間,

任何提示,提示或建議是非常值得歡迎的。

回答

1

我設法解決這個問題,可能是一個更好的方法,但創建一個數組並通過它爲每個項目工作正常。

sortableArray = ($('.grouped-articles-list')); 
    $(sortableArray).each(function(index){ 
    $(sortableArray[index]).sortable({ 
     tolerance: 'pointer', 
     items: "li:not(.sortable_disabled)", 
     start: function(event, ui){ 
      newWeight.length = 0; var resultbefore = $(sortableArray[index]).sortable('toArray');