2012-08-15 75 views
2

我正在做一些html5/jquery拖放功能來重新排序一組DOM元素。我現在想要更改與這些DOM元素對應的對象數組,但我不太確定如何去做。這裏的JavaScript:更改數組的順序以匹配一組DOM元素的順序

var draggedIndex = $('.segmentListItem').index($(draggedItem)); 
var targetIndex = $('.segmentListItem').index($(this)); 
var playlist = jwplayer().getPlaylist(); //MH - the array for which I want to change the order 

if (draggedIndex > targetIndex){ 
    $(draggedItem).insertBefore($(this)); 
    //MH - need to move the playlist item at the index of the dragged item before index the target item as well 
} else { 
    $(draggedItem).insertAfter($(this)); 
    //MH - need to move the playlist item at the index of the dragged item before index the target item as well 

} 

回答

2

如果播放列表是一個普通的數組,而不是一個對象(你reffering把它作爲一個數組),也許是這樣的:

Array.prototype.move = function (old_index, new_index) { 
    if (new_index >= this.length) { 
     var k = new_index - this.length; 
     while ((k--) + 1) { 
      this.push(undefined); 
     } 
    } 
    this.splice(new_index, 0, this.splice(old_index, 1)[0]); 
}; 

var draggedIndex = $('.segmentListItem').index($(draggedItem)); 
var targetIndex = $('.segmentListItem').index($(this)); 
var playlist = jwplayer().getPlaylist(); //MH - the array for which I want to change the order 

if (draggedIndex > targetIndex){ 
    $(draggedItem).insertBefore($(this)); 
    playlist.move(draggedIndex, targetIndex); 
} else { 
    $(draggedItem).insertAfter($(this)); 
    playlist.move(draggedIndex, targetIndex); 
}