Javascript 更改数组的顺序以匹配一组DOM元素的顺序
我正在做一些html5/jquery拖放功能来重新排列一组DOM元素。现在我想更改与这些DOM元素相对应的对象数组,但我不太确定如何更改。下面是javascript:Javascript 更改数组的顺序以匹配一组DOM元素的顺序,javascript,jquery,arrays,sorting,Javascript,Jquery,Arrays,Sorting,我正在做一些html5/jquery拖放功能来重新排列一组DOM元素。现在我想更改与这些DOM元素相对应的对象数组,但我不太确定如何更改。下面是javascript: var draggedIndex = $('.segmentListItem').index($(draggedItem)); var targetIndex = $('.segmentListItem').index($(this)); var playlist = jwplayer().getPlaylist(); //MH
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
}
如果播放列表是一个常规数组,而不是一个对象(您将其视为一个数组),则可能是这样的:
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);
}