Jquery可自动排序

我们可以使用我在每个li中使用的id或idx在运行时对jquery进行排序。 我希望它在运行时排序

这里是小提琴 。 我希望它自动排序,例如

  • 应首先出现
  • 等等。帮助将被赞赏,因为我是新手试图学习jquery。

    这是HTML:

     
    • 3
    • 6
    • 1
    • 4
    • 9
    • 2
    • 8
    • 5
    • 11
    • 7
    • 10
    • 12

    这是JS:

     $(function() { $( "#sortable" ).sortable(); $(":button").click(function(){ $(this).parent().remove(); var arr=$("#sortable").sortable('toArray'); text=arr.toString(); alert(text); }); }); 

    这是CSS:

     #sortable { list-style-type: none; margin: 0; padding: 0; } #sortable li { margin: 3px 3px 3px 0; padding: 1px; float: left; width: 100px; height: 90px; font-size: 4em; text-align: center; } 

    我还引入了一堆库和CSS(不确定JSFiddle是否需要它):

            

    看一下这个

    http://jsfiddle.net/wmaqb/2/

    使用标准jQuery库和.sort()方法,您可以指定用于对对象数组进行排序的函数。

     $('#sort').click(function() { var mylist = $('#sortable'); var listitems = mylist.children('li').get(); listitems.sort(function(a, b) { var compA = parseFloat($(a).attr('id')); var compB = parseFloat($(b).attr('id')); return (compA < compB) ? -1 : (compA > compB) ? 1 : 0; }); $.each(listitems, function(idx, itm) { mylist.append(itm); }); }); 

    一旦你对这个数组进行了排序,你可以简单地用.each()循环来命令它们