按日期合并两个列表jquery

时间:2012-05-12 15:23:08

标签: javascript jquery list merge

让我们说我们有这个标记:

<div id="container">
    <ul></ul>
    <ul></ul>
</div>

<li>的格式如下:

<ul>
   <li>
     <span class="title">Title of the article</span>
     <span class="date" data-value="[TIMESTAMP]">Pretty Date</span>
   </li>
</ul>

我需要做的是:

  • 如果视口宽度足够大:显示两个列表

  • 如果视口宽度很小:按日期合并两个列表

      

    var min = 760; $(窗口).resize(函数(){       var width = $(window).width();       if(width&lt; = min){           merge_lists();       }});

我在弄清楚如何做到这一点时遇到了一些麻烦:

function merge_lists(){
     /* shall i run 2 .each function and store it in an array, order by date (how?) and
        regenerate a new list?
      */
}

1 个答案:

答案 0 :(得分:1)

我认为你喜欢这样的事情:

<强> HTML:

<div id="container">
    <ul>
        <li>
         <span class="title">Title of the article</span>
         <span class="date" data-value="2012/05/01">2012/05/01</span>
       </li>
    </ul>
    <ul>
        <li>
         <span class="title">Title of the article</span>
         <span class="date" data-value="2012/05/05">2012/05/05</span>
       </li>
    </ul>
    <ul>
        <li>
         <span class="title">Title of the article</span>
         <span class="date" data-value="2012/04/10">2012/04/10</span>
       </li>
    </ul>
</div>

<强> jQuery的:

var mainlists = $('#container ul'),
    min = 550;

function merge_lists() {
     if (!$('#container').hasClass('merged')) {
        var temp = mainlists.clone(true),
            lists = $('li', temp);
        lists.sort(function(a, b) {
            var d1 = $('span.date', a).data('value'),
                d2 = $('span.date', b).data('value');
            if (new Date(d1).getTime() > new Date(d2).getTime()) return 1;
        });
        $('#container').empty().append($('<ul>', {
            html: lists
        }));
        $('#container').addClass('merged');
    }
}

function restore_lists() {
    if ($('#container').hasClass('merged')) {
       $('#container').empty().append(mainlists.clone(true));
       $('#container').removeClass('merged');
    }
}

$(window).resize(function() {
    var winWidth = $(window).width(),
        winHeight = $(window).height();
    $('#resolution').html(winWidth + 'px x ' + winHeight + 'px');
    if (winWidth < min) {
        merge_lists();
        $('body').css('background', '#ddd');
    } else {
        restore_lists();
        $('body').css('background', '#fff');
    }
});

<强> DEMO