How may I sort a list alphabetically using jQuery?

后端 未结 10 2145
灰色年华
灰色年华 2020-11-21 23:13

I\'m a bit out of my depth here and I\'m hoping this is actually possible.

I\'d like to be able to call a function that would sort all the items in my list alphabeti

10条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 23:36

    You do not need jQuery to do this...

    function sortUnorderedList(ul, sortDescending) {
      if(typeof ul == "string")
        ul = document.getElementById(ul);
    
      // Idiot-proof, remove if you want
      if(!ul) {
        alert("The UL object is null!");
        return;
      }
    
      // Get the list items and setup an array for sorting
      var lis = ul.getElementsByTagName("LI");
      var vals = [];
    
      // Populate the array
      for(var i = 0, l = lis.length; i < l; i++)
        vals.push(lis[i].innerHTML);
    
      // Sort it
      vals.sort();
    
      // Sometimes you gotta DESC
      if(sortDescending)
        vals.reverse();
    
      // Change the list on the page
      for(var i = 0, l = lis.length; i < l; i++)
        lis[i].innerHTML = vals[i];
    }
    

    Easy to use...

    sortUnorderedList("ID_OF_LIST");
    

    Live Demo →

提交回复
热议问题