简体   繁体   English

如何自动重新排序可排序的jQuery UI列表?

[英]How to automatically reorder a Sortable jQuery UI list?

I have 2 jQuery UI sortable lists (http://jqueryui.com/demos/sortable/#connect-lists). 我有2个jQuery UI可排序列表(http://jqueryui.com/demos/sortable/#connect-lists)。

I drag items from list A (catalog) to list B (basket). 我将项目从列表A(目录)拖到列表B(购物篮)。

What I want is for the lists (A and B) to reorder themselves automatically when an item is added (sorted by price). 我想要的是列表(A和B)在添加项目时自动重新排序 (按价格排序)。 So when an item is dropped into the basket, it will go to its position (top/middle/bottom) according to its price. 因此,将物品放入购物篮时,它会根据其价格转到其位置(顶部/中间/底部)。

You should use the "receive" event form sortable in conjunction with the sort method. 您应该将“ receive”事件形式与sort方法结合使用。

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

}

I don't think there is a built in sorting mechanism like you've describted for the jQuery UI sortable lists. 我认为没有像您描述的jQuery UI可排序列表那样的内置排序机制。 However, you could use this jQuery plugin to manually sort the items. 但是,您可以使用此jQuery插件手动对项目进行排序。 It's very light weight and lets you control how things are sorted by defining a sorting function. 它的重量很轻,可让您通过定义排序功能来控制事物的排序方式。

You could attach the sorting routine to the receive event of your "basket list." 您可以将排序例程附加到“购物篮列表”的receive事件。 In that event, you would sort the items in the basket list by looking at their price and comparing them numerically. 在这种情况下,您可以通过查看购物篮价格并对其进行数字比较来对购物篮列表中的商品进行排序。 Pay attention to the second parameter of sortElements . 注意sortElements的第二个参数。 It allows you to tell the sorter what element you actually want to move. 它使您可以告诉分选器您实际要移动的元素。 Though in this case, just moving the li item might be fine. 尽管在这种情况下,仅移动li项目可能会很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM