Separate unsorted list by letter in jQuery?
I'm new to jQuery and I'd like to take an unsorted list and do the following: http://i.min.us/idAMoq.png
How would one accomplish separating list items based on the beginni开发者_如何学JAVAng letter?
Thanks!
I've used this example HTML:
<ul>
<li>Array</li>
<li>Beta</li>
<li>Application</li>
<li>Revolver</li>
<li>Pilot</li>
</ul>
Include jQuery library in the <head>
:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
jQuery (added after UL or in $(function(){/*code here*/})
):
var output={};
$('ul li').each(function(i,v){
var l=$(this).text().substring(0,1).toUpperCase();
if(typeof(output[l])=="undefined") output[l]=[];
output[l].push($(this).text());
});
$('ul').empty();
for(var i in output){
$('ul').append('<li><p>'+i+'</p></li>');
for(var j in output[i]){
$('ul').append('<li>'+output[i][j]+'</li>');
}
}
and at the end you'll get this HTML:
<ul>
<li><p>A</p></li>
<li>Array</li>
<li>Application</li>
<li><p>B</p></li>
<li>Beta</li>
<li><p>R</p></li>
<li>Relolver</li>
<li><p>P</p></li>
<li>Pilot</li>
</ul>
Hi, small update, pure JS version should be working with prototype, jQuery or without any:)
var output={},string="";
var myul=document.getElementById('list');
var myli=myul.getElementsByTagName('li');
for(var x=0;x<myli.length;x++){
var l=myli[x].innerHTML.substring(0,1).toUpperCase();
if(typeof(output[l])=="undefined") output[l]=[];
output[l].push(myli[x].innerHTML);
}
for(var i in output){
string+='<li><p>'+i+'</p></li>';
for(var j in output[i])string+='<li>'+output[i][j]+'</li>';
}
myul.innerHTML=string;
Just stick it below the code or in any onload/ready statement.
Cheers
G.
精彩评论