Last active
December 20, 2015 14:18
-
-
Save WenLiangTseng/6145063 to your computer and use it in GitHub Desktop.
jQuery: sorting lists alphabetically 按照英文字母排序 List 清單
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($) { | |
$.fn.listSorter = function(options) { | |
var that = this; | |
var settings = { | |
order: 'asc' | |
}; | |
options = $.extend(settings, options); | |
var items = $('li', that).get(); | |
var filtered = ''; | |
switch (options.order) { | |
case 'asc': | |
case 'desc': | |
break; | |
default: | |
return new Error('Invalid option'); | |
} | |
return that.each(function() { | |
if (options.order == 'asc') { | |
var asc = items.sort(function(a, b) { | |
var $text1 = $(a).text(); | |
var $text2 = $(b).text(); | |
return $text1[0].toLowerCase() > $text2[0].toLowerCase(); | |
}); | |
for (var i = 0; i < asc.length; i++) { | |
filtered += '<li>' + $(asc[i]).text() + '</li>'; | |
} | |
$(that).html(filtered); | |
} else { | |
var desc = items.sort(function(a, b) { | |
var $text1 = $(a).text(); | |
var $text2 = $(b).text(); | |
return $text1[0].toLowerCase() < $text2[0].toLowerCase(); | |
}); | |
for (var j = 0; j < desc.length; j++) { | |
filtered += '<li>' + $(desc[j]).text() + '</li>'; | |
} | |
$(that).html(filtered); | |
} | |
}); | |
}; | |
})(jQuery); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<ul id="test"> | |
<li>Aquae</li> | |
<li>Zaphiro</li> | |
<li>Conundrum</li> | |
<li>Facet</li> | |
<li>Venus</li> | |
<li>Oppidum</li> | |
<li>Ideo</li> | |
<li>Xeno</li> | |
<li>Lambda</li> | |
<li>Sicut</li> | |
</ul> | |
<script type="text/javascript"> | |
jQuery(document).ready(function($){ | |
$('#asc').click(function(e) { | |
e.preventDefault(); | |
$('#test').listSorter(); | |
}); | |
$('#desc').click(function(e) { | |
e.preventDefault(); | |
$('#test').listSorter({ | |
order: 'desc' | |
}); | |
}); | |
}); | |
</script> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery: sorting lists alphabetically | |
The original reference: | |
http://gabrieleromanato.name/jquery-sorting-lists-alphabetically/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment