Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
673 views
in Technique[技术] by (71.8m points)

jquery - How to sort div's by content date

I'm trying to sort div's by content date... What i've got is sorting. But not by date...

HTML

 <div id="all_elements">

            <!-- one element -->
            <div class="element">
                    <div class="display-number">02</div>
                    <div class="year">20-10-2011</div>
            </div><!-- element -->

            <!-- one element -->
            <div class="element">
                    <div class="display-number">03</div>
                    <div class="year">22-09-2011</div>
            </div><!-- element -->

            <!-- one element -->
            <div class="element">
                    <div class="display-number">01</div>
                    <div class="year">01-12-2011</div>
            </div><!-- element -->

            <!-- one element -->
            <div class="element">
                    <div class="display-number">04</div>
                    <div class="year">01-06-2011</div>
            </div><!-- element -->

            <!-- one element -->
            <div class="element">
                    <div class="display-number">05</div>
                    <div class="year">01-06-2010</div>
            </div><!-- element -->

        </div> <!--all_elements-->

JQUERY

<script>
        function sortDescending(a, b) {
            return $(a).find(".year").text() < $(b).find(".year").text() ? 1 : -1;
        };
        $(document).ready(function() {
            $('#all_elements .element').sort(sortDescending).appendTo('#all_elements');
        }); 
    </script>

I know i need a function to figure out the content is a date.. Just don't know how...

Who can help me out?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do:

   function sortDescending(a, b) {
     var date1  = $(a).find(".year").text();
       date1 = date1.split('-');
     date1 = new Date(date1[2], date1[1] -1, date1[0]);
     var date2  = $(b).find(".year").text();
       date2= date2.split('-');
     date2= new Date(date2[2], date2[1] -1, date2[0]);

     return date1 < date2 ? 1 : -1;
    };
    $(document).ready(function() {
        $('#all_elements .element').sort(sortDescending).appendTo('#all_elements');
    }); 

EDIT - corrected the typo according to the comment! Fiddle here http://jsfiddle.net/TsZeg/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...