简体   繁体   中英

.sort not working in IE (IE 9)

Ive worked for a few days on this one. I have a script that is dynamically creating rows in a table. The final output looks like this:

<table id="event-list">
    <tr id="event0" value="04/04/2000">
        <td>My Third Event</td>
        <td>Apr 4</td>
        <td>Omaha, NE</td>
        <td></td>
    </tr>
    <tr id="event4" value="04/24/2000">
        <td>USA Triathlon National Championships Collegiate Club</td>
        <td>Apr 24</td><td>Clemson, SC</td>
        <td></td>
    </tr>
    <tr id="event2" value="07/17/2000">
        <td>My Second Event</td><td>Jul 17</td>
        <td>Omaha, NE</td>
        <td></td>
    </tr>
    <tr id="event3" value="08/17/2000">
        <td>My Second Event</td>
        <td>Aug 17</td>
        <td>Ames, IA</td>
        <td></td>
    </tr>
    <tr id="event1" value="10/26/2000">
        <td>ZTA 5K For Breast Cancer Awareness</td>
        <td>Oct 26</td>
        <td>Omaha, NE</td>
        <td></td>
    </tr>
</table>

Im using the below script to sort each row by date:

$('#event-list tr').sort(function(a,b) {
       return new Date($(a).attr('value')) < new Date($(b).attr('value'));

}).each(function(){
       $('#event-list').prepend(this);

});

It works fine in Chrome and Firefox, but in IE - the list is just reversing in the opposite order.

Any thoughts on a reason or work around? Thanks in advance.

Your sort function is incorrect. A sort function can't just return a boolean telling whether one element is greater than the other. It has to handle all three cases: less than, greater than, and equal.

  • If a < b, return a negative value
  • If a > b, return a positive value
  • If a == b, return zero

It's easy to change your sort function to accomplish this. Instead of comparing the two values with the < operator, simply subtract them:

   return new Date($(a).attr('value')) - new Date($(b).attr('value'));

If that gives you the opposite order from what you want, reverse it:

   return new Date($(b).attr('value')) - new Date($(a).attr('value'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM