我有2個jQuery UI可排序列表(http://jqueryui.com/demos/sortable/#connect-lists)。如何自動重新排序可排序的jQuery UI列表?
我將項目從列表A(目錄)拖到列表B(籃子)。
我想要的是列表(A和B)自動重新排列自己當一個項目被添加(按價格排序)。所以當一件物品掉入籃筐時,它會根據其價格進入其位置(上/中/下)。
我有2個jQuery UI可排序列表(http://jqueryui.com/demos/sortable/#connect-lists)。如何自動重新排序可排序的jQuery UI列表?
我將項目從列表A(目錄)拖到列表B(籃子)。
我想要的是列表(A和B)自動重新排列自己當一個項目被添加(按價格排序)。所以當一件物品掉入籃筐時,它會根據其價格進入其位置(上/中/下)。
我不認爲有像您已經描述過的jQuery UI可排序列表一樣的內置排序機制。但是,您可以使用this jQuery plugin手動對項目進行分類。它的重量非常輕,您可以通過定義排序功能來控制事物的排序方式。
您可以將排序例程附加到「購物籃列表」的receive
事件中。在這種情況下,您可以通過查看價格並將其與數值進行比較來對購物籃列表中的物品進行分類。注意第二個參數sortElements
。它允許您告訴分揀機您實際上想要移動的元素。雖然在這種情況下,只是移動li
項目可能沒問題。
您應該使用可以與排序方法一起排序的「接收」事件表單。
$('.list_a, .list_b').sortable({
receive: function(){
$('.list_a').html($('.list_a').get().sort(sortByPrice));
$('.list_b').html($('.list_b').get().sort(sortByPrice));
// As we replaced the content of the list, you probably need to
// make it sortable again... kind of a big hack
}
});
function sortByPrice(a, b){
// The parseFloat will not work if you have text before the price
// in the price container.
var price_a = parseFloat($('.price_selector', a).text());
var price_b = parseFloat($('.price_selector', b).text());
if(price_a < price_b) return -1;
if(price_a > price_b) return 1;
return 0;
}
這個排序函數在哪裏定義?我沒有在文檔中看到它? – arb
Oups!調整了我的答案。排序是一種基本的JavaScript數組方法。因此,通過獲取標準數組,可以對其進行排序,並將其作爲內容進行分配。我可以推薦使用TinySort嗎? [鏈接](http://tinysort.sjeiti.com/) – jValdron
我使用TinySort這個完全相同的場景,它可以很好地工作而不會使用Sortable – dstarh