Jquery. Order a list of names alphabetically
I got a list of names (firstname and lastname) on a page. I want the user to be able to sort this list on either firstname or lastn开发者_如何学编程ame using jQuery (or normal javascript). How can this be done?
<ul>
<li>Michael Scott</li>
<li>Jonathan Torry</li>
</ul>
Very thankful for all input!
Array.sort() is what you need
var items = [];
$('ul li').each(function(){
items.push($(this).html());
})
items.sort();
Example here : http://jsfiddle.net/jomanlk/7UzNZ/
Try my plugin http://www.athos99.com/listorder/type.html
For ordering fistname and lastname, change your list like this :
<ul id="ul1">
<li><span>Michael</span> <span>Scott</span></li>
<li><span>Jonathan</span> <span>Torry</span></li>
</ul>
For ordering by firstname
$('#ul1').listorder( { child:'li', childValue:function(){return $(this.children([0]).text();} });
For ordering by lastname
$('#ul1').listorder( { child:'li', childValue:function(){return $(this.children([1]).text();} });
$(this.children([0]) select the 1st span
$(this.children([1]) select the 2nd span
精彩评论