且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用jQuery组列表项

更新时间:2023-12-05 15:01:52

我已经写了注释评论 此处( jsFiddle ) 此处( jsBin ).

I've written a commented solution here (jsFiddle) and here (jsBin).

(两个链接具有相同的内容,但是jsFiddle有时很慢,因此您可能想改用jsBin)

希望您会喜欢它!

<ul id="mainList">
    <li><span class="date">2011 05 01</span><p>Text...</p></li>
    <li><span class="date">2011 12 01</span><p>Text...</p></li>
    <li><span class="date">2011 05 01</span><p>Text...</p></li>
    <li><span class="date">2011 04 01</span><p>Text...</p></li>
    <li><span class="date">2011 04 01</span><p>Text...</p></li>
    <li><span class="date">2010 03 01</span><p>Text...</p></li>
    <li><span class="date">2010 02 01</span><p>Text...</p></li>
</ul>


JAVASCRIPT

// Month number to string
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

// Sorting the <li> by year
$("#mainList li").sort(function(a,b) {
    var yearA = $(a).children("span").text().split(" ")[0],
        yearB = $(b).children("span").text().split(" ")[0];
    return yearA < yearB;
}).appendTo($("#mainList"));

// Grouping the <li> by year
$("#mainList li").each(function() {
    var year = $(this).children("span").text().split(" ")[0];
    // If the grouping <li> doesn't exist, create it
    if ($("#mainList li.year." + year).length === 0) {
        $("#mainList").append($('<li class="year ' + year + '">' + year + '<ul></ul></li>'));
    }
    // Add the current <li> to the corresponding grouping <li>
    $(this).appendTo($("#mainList li.year." + year + " ul"));
});

// Sorting the <li> by month inside each grouping <li>
$("#mainList li.year ul").each(function() {
    $(this).children("li").sort(function(a,b) {
        var monthA = $(a).children("span").text().split(" ")[1],
            monthB = $(b).children("span").text().split(" ")[1];
        return monthA < monthB;
    }).appendTo($(this));
});

// Grouping the <li> by month inside each grouping <li>
$("#mainList li.year ul").each(function() {
    $this = $(this);
    $this.children("li").each(function() {
        var month = $(this).children("span").text().split(" ")[1];
        // If the grouping <li> doesn't exist, create it
        if ($this.find("li.month." + month).length === 0) {
            $this.append($('<li class="month ' + month + '">' + months[month-1] + '<ul></ul></li>'));
        }
        // Add the current <li> to the corresponding grouping <li>
        $(this).appendTo($this.find("li.month." + month + " ul")).addClass("item");
    });
});