8

我想知道是否可以让 JQuery UI 可排序默认值按字母顺序排序。如果是这样,如果我将项目添加到可排序中,是否也可以实时按字母顺序排序?下面是我的代码:

// Adds item to sortable list
$(".addButton").click(function(e) {
    e.preventDefault();
    // set var item to be the string inputted by the user
    var item = $("input[name='brewItem']").val();
    // parses input string, splitting at commas into liArray containing substrings as elements
    var liArray = item.split(", ");
    // for loop to add each brew to the sortable list (length-1 because last element in array is empty string)
    for (var i = 0; i < liArray.length-1; i++) {
        // sets var $li to the string in the ith index of liArray
        var $li = $("<li class='ui-state-default'/>").text(liArray[i]);



        // adds var $li to gui
        $("#sortable").append($li);
    };
    // refreshes the page so var $li shows up
    $("#sortable").sortable("refresh");
});

我不太确定在哪里或如何实现这一点。任何帮助表示赞赏,谢谢!

4

2 回答 2

17

您需要对其进行调整以使其按需要排序。

试试这个:-小提琴

使用自定义排序方法

 function sort() {
    var sortableList = $('#sortable');
    var listitems = $('li', sortableList);

    listitems.sort(function (a, b) {

        return ($(a).text().toUpperCase() > $(b).text().toUpperCase())  ? 1 : -1;
    });
    sortableList.append(listitems);

}

在您的可排序的创建事件Create和按钮单击中调用它

$("#sortable").sortable({
    create: function (event, ui) {
        sort();
    }
});

或扩展 jquery ui 可排序小部件以包含您的自定义排序逻辑。

于 2013-04-15T04:50:07.827 回答
0

实例化可排序

var $sortable =$("#sortable").sortable(options);

不要因为对 dom 的不必要访问而使浏览器不堪重负

在事件处理程序之前,缓存您的输入

var $brew=$("input[name='brewItem']");

通过创建一个 html 字符串来优化您的附加

你可以在你的处理程序的一行中使用 join & do it

$('<li>'+ $brew.val().split(", ").join('</li><li>')+'</li>').appendTo($sortable) ;

注意:如果 li 集被包装,性能会更好,但在你的情况下,你需要在之后解包......不能说哪个会更快

$sortable.sortable('refresh')   
于 2013-04-15T03:59:52.847 回答