admin管理员组

文章数量:1431918

I need to sort the list ascending or descending with ID value of the LI tag once I click the sort button. If it is in ascending order, it must sort to descending and vice versa.

eg:

 <ul id="place-list">
      <li id="0">Paris</li>
      <li id="1">greece</li>
      <li id="2">London</li>
 </ul>

I need to sort it without using the tsort function in jQuery-tinysort. How can I do this?

I need to sort the list ascending or descending with ID value of the LI tag once I click the sort button. If it is in ascending order, it must sort to descending and vice versa.

eg:

 <ul id="place-list">
      <li id="0">Paris</li>
      <li id="1">greece</li>
      <li id="2">London</li>
 </ul>

I need to sort it without using the tsort function in jQuery-tinysort. How can I do this?

Share Improve this question edited Jan 27, 2013 at 0:10 Shoe 76.3k38 gold badges176 silver badges278 bronze badges asked Jan 26, 2013 at 22:25 user2014494user2014494 211 silver badge1 bronze badge 5
  • 3 StackOverflow is not a "write my code for me" site. It's a "help me with the code I've written" site. – Raymond Chen Commented Jan 26, 2013 at 22:27
  • This: stackoverflow./questions/1134976/… – Tomer Arazy Commented Jan 26, 2013 at 22:27
  • Don't use numbers for IDs. Not only are they hard to keep unique, they're also non-standard in HTML4 and in my opinion dubious in HTML5. – Niet the Dark Absol Commented Jan 26, 2013 at 22:27
  • possible duplicate of Sort element by numerical value of data attribute – Felix Kling Commented Jan 26, 2013 at 22:33
  • I think it's a fair question if new, though need to know if new to jquery or javascript in general to be able to give a good answer – Rob Sedgwick Commented Jan 26, 2013 at 22:37
Add a ment  | 

4 Answers 4

Reset to default 2

Can use sort() on collection of jQuery elements:

var $list = $('#place-list');    
/* store lastSort direction in button data*/
$('button').data('lastSort', 'asc').click(function() {
    var $btn=$(this), $items = $list.children(), lastSort=$btn.data('lastSort');
    var direction = lastSort=='asc' ? 'desc' :  'asc';
   $btn.data('lastSort',direction);
    $list.empty().append($items.sort(directionSort[direction]));
});


var directionSort = {
    asc: function (a, b) {
        return a.id < b.id ? -1 : 1;
    },
    desc: function (a, b) {
        return a.id > b.id ? -1 : 1;
    }
}

DEMO: http://jsfiddle/XAutV/1/

Don't use jQuery when it isn't needed.

function sortList() {
    sortList.direction = sortList.direction ? false : true;
    var arr = [], list = document.getElementById('place-list'),
        c = list.children, l = c.length, i;
    for(i=0; i<l; i++) arr[i] = c[i]; // "convert" NodeList to array
    arr.sort(function(a,b) {return a.id < b.id ? -1 : 1;}); //sorting function ends here.
    if( !sortList.direction) arr = arr.reverse();
    for(i=0; i<l; i++) list.appendChild(arr[i]);
};

I added a #sort element that can be clicked to sort the elements

$("#sort").click(function(){
    var sortedLis = [];
    var lis = $("#place-list").find("li");
    lis.remove();

    var descending = $(lis[0]).attr("id") == lis.length -1;
    lis.each(function(index, element){
        if(!descending){
          sortedLis[lis.length - $(element).attr("id")] = element;
        }else{
            sortedLis[$(element).attr("id")] = element;
        }
    });

    $("#place-list").append(sortedLis);
});

Example

You also could use .map()

Also I would change id="" to data-id="".

HTML

<ul id="place-list">
    <li data-id="4">Tokyo 4</li>
    <li data-id="0">Paris 0</li>
    <li data-id="5">Frankfurt 5</li>
    <li data-id="2">London 2</li>
    <li data-id="1">greece 1</li>
    <li data-id="3">Munich 3</li>
</ul>
<button id="asc">ASC</button>
<button id="desc">DESC</button>

jQuery

var sortArray = function (items, inverse) {
    var inverse = inverse || false;

    var sortedArray = items.map(function () {
        return {
            id: $(this).data("id"),
            element: $(this)[0].outerHTML
        };
    });

    var appendTo = items.parent();
    items.remove();

    sortedArray.sort(function (a, b) {
        return a.id > b.id ? (inverse ? -1 : 1) : (inverse ? 1 : -1);
    });

    sortedArray.each(function () {
        $(appendTo).append(this.element);
    });
}

$("#asc").click(function () {
    sortArray($("#place-list").find("li"));
});

$("#desc").click(function () {
    sortArray($("#place-list").find("li"), true);
});

Example

http://jsfiddle/995dY/

本文标签: javascriptSorting li by id valueStack Overflow