1

我有2个jQuery UI可排序列表(http://jqueryui.com/demos/sortable/#connect-lists)。如何自动重新排序可排序的jQuery UI列表?

我将项目从列表A(目录)拖到列表B(篮子)。

我想要的是列表(A和B)自动重新排列自己当一个项目被添加(按价格排序)。所以当一件物品掉入篮筐时,它会根据其价格进入其位置(上/中/下)。

回答

0

我不认为有像您已经描述过的jQuery UI可排序列表一样的内置排序机制。但是,您可以使用this jQuery plugin手动对项目进行分类。它的重量非常轻,您可以通过定义排序功能来控制事物的排序方式。

您可以将排序例程附加到“购物篮列表”的receive事件中。在这种情况下,您可以通过查看价格并将其与数值进行比较来对购物篮列表中的物品进行分类。注意第二个参数sortElements。它允许您告诉分拣机您实际上想要移动的元素。虽然在这种情况下,只是移动li项目可能没问题。

1

您应该使用可以与排序方法一起排序的“接收”事件表单。

$('.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; 

} 
+0

这个排序函数在哪里定义?我没有在文档中看到它? – arb

+1

Oups!调整了我的答案。排序是一种基本的JavaScript数组方法。因此,通过获取标准数组,可以对其进行排序,并将其作为内容进行分配。我可以推荐使用TinySort吗? [链接](http://tinysort.sjeiti.com/) – jValdron

+1

我使用TinySort这个完全相同的场景,它可以很好地工作而不会使用Sortable – dstarh