使用jQuery按日期对表进行排序

时间:2018-06-27 20:47:28

标签: javascript jquery arrays html5 tablesorter

我正在尝试使用Jquery按日期,日期/月份/年份(递增和递减)对单击数组进行排序。 但是,当我单击“日期”按钮时,表格未正确排序。

这是我的脚本: https://jsfiddle.net/mr8vnj57/9/

var compare = {                           // Declare compare object
  name: function(a, b) {                  // Add a method called name
    a = a.rep
    lace(/^the /i, '');          // Remove The from start of parameter
    b = b.replace(/^the /i, '');          // Remove The from start of parameter

    if (a < b) {                          // If value a is less than value b
      return -1;                          // Return -1
    } else {                              // Otherwise
      return a > b ? 1 : 0;               // If a is greater than b return 1 OR
    }                                     // if they are the same return 0
  },
  duration: function(a, b) {              // Add a method called duration
    a = a.split(':');                     // Split the time at the colon
    b = b.split(':');                     // Split the time at the colon

    a = Number(a[0]) * 60 + Number(a[1]); // Convert the time to seconds
    b = Number(b[0]) * 60 + Number(b[1]); // Convert the time to seconds

    return a - b;                         // Return a minus b
  },
  date: function(a, b) {                  // Add a method called date
    a = new Date(a);                      // New Date object to hold the date
    b = new Date(b);                      // New Date object to hold the date

    return a - b;                         // Return a minus b
  }
};

$('.sortable').each(function() {
  var $table = $(this);                     // This sortable table
  var $tbody = $table.find('tbody');        // Store table body
  var $controls = $table.find('th');        // Store table headers
  var rows = $tbody.find('tr').toArray();   // Store array containing rows

  $controls.on('click', function() {        // When user clicks on a header
    var $header = $(this);                  // Get the header
    var order = $header.data('sort');       // Get value of data-sort attribute
    var column;                             // Declare variable called column

    // If selected item has ascending or descending class, reverse contents
    if ($header.is('.ascending') || $header.is('.descending')) {  
      $header.toggleClass('ascending descending');    // Toggle to other class
      $tbody.append(rows.reverse());                // Reverse the array
    } else {                                        // Otherwise perform a sort                            
      $header.addClass('ascending');                // Add class to header
      // Remove asc or desc from all other headers
      $header.siblings().removeClass('ascending descending'); 
      if (compare.hasOwnProperty(order)) {  // If compare object has method
        column = $controls.index(this);         // Search for column’s index no

        rows.sort(function(a, b) {               // Call sort() on rows array
          a = $(a).find('td').eq(column).text(); // Get text of column in row a
          b = $(b).find('td').eq(column).text(); // Get text of column in row b
          return compare[order](a, b);           // Call compare method
        });

        $tbody.append(rows);
      }
    }
  });
});
td {
	background-color: #fff;}
table.sortable th:hover {
	cursor: pointer;}
th.ascending, th.descending, table.sortable th:hover {
	background-color: #00cccc;
	color: #fff;}

/* Arrows for table sorting */
th.ascending:after {
	font-size: 60%;
    content: '\25B2';
    float: left;
	padding: 4px 5px 0px 0px;}
th.descending:after {
	font-size: 60%;
    content: '\25BC';
    float: left;
	padding: 4px 5px 0px 0px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="sortable">
      <thead>
        <tr>
          <th >Date</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>16-07-2014</td>
        </tr>
        <tr>
          <td>28-02-2014</td>
        </tr>
        <tr>
          <td>10-04-2012</td>
        </tr>
        
         <tr>
          <td>10-04-2016</td>
        </tr>
 
      </tbody>
    </table>

这告诉我

日期减少: 2016年10月4日 2012年10月4日 2014年2月28日 2014年6月16日

日期增加: 2014年7月16日 2014年2月28日 2012年10月4日 2016年10月4日

您还有其他解决方案吗?您可以为我更正脚本吗?

谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

有两个问题:

  • 代码正在标题单元格中寻找data-sort属性。未找到任何内容,因此排序未按预期使用date函数。
  • 日期格式为“ DD-MM-YYYY”。使用new Date()要求使用Date.parse()方法识别的格式(IETF-compliant RFC 2822 timestamps,还有version of ISO8601;是从MDN dateString parameter复制的)。我选择使用new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);格式。

== Updated demo ==

要解决上述问题,请添加data-sort属性:

<th data-sort="date">Date</th>

并按如下所示修改compare.date函数:

date: function(a, b) {                  // Add a method called date
  a = a.split('-');
  b = b.split('-');
  a = new Date(a[2], a[1] - 1, a[0]);   // New Date object to hold the date
  b = new Date(b[2], b[1] - 1, b[0]);   // New Date object to hold the date
  return a - b;                         // Return a minus b
}