开发者

Advance grouping of List Items - Jquery

I have a list like

<ul>
<li> hgh55jjj </li>
<li> abc99xyz </li>
<li> hgf88hjk </li>
<li> ........ </li>
<li> ........ </li>
<li> def99bnb </li>
<li> gjj77hkj </li>
<li> hgh55fhj </li>
</ul>

I want this开发者_如何学运维 to be formatted to a grouped list based on the two digits inside the text in such a way that all 99 items come together. And I also want a nav bar which will browse thru the groups. I need check box beside the list items, but I believe that could be done without mixing this part with.


I'll get you started, but I'm leaving you the navigation menu.
First, here's an easy way to get the number (you can do it in another way, based on your real data):

function getKey(fullText){
    return fullText.match(/\d\d/);
}

next, this code (in document.ready, of course), takes the <li>s, and places them in an associated array, based on the key:

var items = $('li');
var groups = [];
items.each(function(){
    var li = $(this);
    var g = 'List' + getKey(li.text());
    if(!groups[g])
      groups[g] = [];
    groups[g].push(li);
});

Finally, for every group we create it's own <ul>, with name=id=List99 (this will help when you build the navigation menu):

for(group in groups){
    var ul = $('<ul />').attr('id', group).attr('name', group);
    var lis = groups[group];
    for(i = 0;i<lis.length;i++){
        ul.append(lis[i]);
    }
    ul.appendTo('body');
}

Now, this may not be the best way of doing it, but it should be a good start.
You can see it in action here: http://jsbin.com/inubi3 ,
and play with the code here: http://jsbin.com/inubi3/edit

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜