【问题标题】:How to automatically reorder a Sortable jQuery UI list?如何自动重新排序可排序的 jQuery UI 列表?
【发布时间】:2011-11-29 18:20:45
【问题描述】:

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

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

我想要的是列表(A 和 B)在添加项目时自动重新排序(按价格排序)。所以当一个物品被放入篮子时,它会根据它的价格去到它的位置(顶部/中间/底部)。

【问题讨论】:

    标签: javascript jquery jquery-ui jquery-ui-sortable jquery-ui-draggable


    【解决方案1】:

    您应该将“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;
    
    }
    

    【讨论】:

    • 这个排序函数是在哪里定义的?我在文档中没有看到它?
    • 哎呀!调整了我的答案。排序是一种基本的 JavaScript 数组方法。因此,通过获取标准数组,您可以对其进行排序,并将其分配为内容。我可以推荐使用 TinySort 吗? link
    • 我在同样的场景中使用 TinySort,它在不破坏 Sortable 的情况下工作得很好
    【解决方案2】:

    我认为没有像您为 jQuery UI 可排序列表所描述的那样内置排序机制。但是,您可以使用 this jQuery plugin 手动对项目进行排序。它的重量很轻,让您可以通过定义排序函数来控制事物的排序方式。

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

    【讨论】:

      猜你喜欢
      • 2010-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      • 2010-11-05
      相关资源
      最近更新 更多