2010-01-14 53 views
10

如何更改一次由JS「jQuery.sortable」應用的列表的順序。jQuery.sortable。通過JS更改訂單

例如:

<ul id="mylist"> 
    <li>1</li> 
    <li>2</li> 
    <li>3</li> 
    <li>4</li> 
    <li>5</li> 
</ul> 

var x_sortable_list = $("mylist").sortable(); 

然後,假設此工作:

x_sortable_list.changeOrder([ 
{item:1, newOrder:2 }, 
{item:2, newOrder:1 }, 
{item:3, newOrder:3 } 
]); 

回答

11

正如SPARR說,沒有辦法直接使用sortable對它們進行排序,但你仍然可以像手動移動:

$("#mylist li:eq(1)").insertAfter($("#mylist li:eq(2)")); 
1

的排序提供了一個用戶界面,用於重排的項目。要以編程方式重新排列它們,您仍然需要自己操作元素,手動或使用其他插件。

+7

是的,這是我的問題,我該怎麼做呢? – 2010-01-14 21:26:41

16

像其他人所說的,這有什麼好做的排序()功能。相反,你需要檢索列表中的項目,改變他們的立場,然後明確,在新的秩序又重新插入列表項:

// Get your list items 
var items = $('#mylist').find('li'); 

// The new index order for each item 
var order = [4, 2, 0, 1, 3]; 

// Map the existing items to their new positions   
var orderedItems = $.map(order, function(value) { 
    return items.get(value); 
}); 

// Clear the old list items and insert the newly ordered ones 
$('#mylist').empty().html(orderedItems); 
+0

工程就像一個魅力! :) – 2016-03-31 16:49:53

+0

工程真的很好。謝謝。 – 2017-11-02 12:46:08