2011-09-20 43 views
3

我想重新排列它們包含的某些值的基礎上的divs。我的代碼如下重新排列科和他們的孩子

HTML

<div id="content_id_1"> 
    <ul> 
    <li> some text, not important for the reordering but it must move with it's parent div</li> 
    <li> some text, not important for the reordering but it must move with it's parent div</li> 
    <li> 
     <div class=‘date--2011-11-11’>2011-11-11’< /div> 
    </li> 
    </ul> 
</div> 
<div id="content_id_2"> 
    <ul> 
    <li> some text, not important for the reordering but it must move with it's parent div</li> 
    <li> some text, not important for the reordering but it must move with it's parent div</li> 
    <li> 
     <div class=‘date--2011-10-10’>2011-10-10’< /div> 
    </li> 
    </ul> 
</div> 

等等......

在改變稱爲#data_filter過濾器,我想主要的div(那些content_id_something)和他們的全部內容是重新排序的日期值...我試圖適應下面的示例(http://stackoverflow.com/questions/2501789/jquery-sort-divs-according-to-content-of-different-sub-divs),但我有點失落...... JQuery:

$("#data_filter").change(function(){ 
    function sortDateASC(a, b){ 
     return $(a).find(div[class^=date--]) > $(b).find(div[class^=date--]) ? 1 : -1; 
    }; 
$(div[class^=date--]) .each(function(){ 
    $(this).parent().parent().parent().sort(sortDateASC); 
    }); 
}) ; 

非常感謝您的幫助!

回答

1

是這樣的:

$("#data_filter").change(function(){ 
    function sortDateASC(a, b){ 
    var keya = new Date($(a).find('div[class^="date--"]').text().replace("'","")).getTime(); 
    var keyb = new Date($(b).find('div[class^="date--"]').text().replace("'","")).getTime(); 
    return keya > keyb ? 1 : keya < keyb ? -1 : 0; 
    } 
    $('div[class^="date--"]') .each(function(){ 
    $(this).closest("#listparent").children().sort(sortDateASC).appendTo("#listparent"); 
    }); 
}); 

在名單被包裹在一個元素與listparent

編輯的ID:這裏有一個小提琴:http://jsfiddle.net/EUkPb/

+0

其實,'''必須被刪除。更新答案。 –

+0

非常感謝你Tentonaxe! '確實是一個錯字 – Raphael

0

你只能比較值,而不是jquery對象。所以你可以嘗試:

return $(a).find(div[class^=date--]).attr('class') > $(b).find(div[class^=date--]).attr('class') ? 1 : -1; 

不知道它是否工作。

+0

謝謝安迪!它確實不幸沒有工作... – Raphael

相關問題