1

我正在使用 jQuery 表格排序器对表格进行排序。它对除具有日期字段的列之外的所有列进行排序。日期具有Sep 3, 2012 这种格式。如何解决这个问题呢?

样品日期:

  • 2012 年 9 月 3 日
  • 2012 年 8 月 9 日
  • 2012 年 6 月 25 日
4

1 回答 1

1

我有一个 tablesorter 的分支,它允许您编写一个解析器,可以从表格单元格属性中提取数据,例如data-attribute.

这个例子中,我有一个不同格式的生日列,但data-date单元格的属性是一致的。

<table> 
<thead> 
  <tr> 
    <th>Name (Last)</th> 
    <th>Originally from...</th> 
    <th>Birthday</th> 
  </tr> 
</thead> 
  <tbody> 
    <tr> 
      <td data-lastname="Allen">Joe Allen</td> 
      <td>South Carolina</td> 
      <td data-date="01-15">Jan 15</td> 
    </tr> 
    <tr> 
      <td data-lastname="Torres">Lisa Torres</td> 
      <td>Maryland</td> 
      <td data-date="03-02">March 2nd</td> <!-- leading zeros needed to sort properly! --> 
    </tr> 
    <tr> 
      <td data-lastname="Franklin">Peter Louis Franklin</td> 
      <td>Coventry</td> 
      <td data-date="12-26">Boxing Day (Dec 26th)</td> 
    </tr> 
    <tr> 
      <td data-lastname="Jones">Maria Consuela de Los Angeles Ortiz Del Toro-Jones</td> 
      <td>Texas</td> 
      <td data-date="05-10">10 Mayo</td> 
    </tr> 
    <tr> 
      <td data-lastname="Bigglesworth">Mike "the Smasher" Bigglesworth</td> 
      <td>Rhode Island</td> 
      <td data-date="06-22">22nd of June</td> 
    </tr> 
    <tr> 
      <td data-lastname="Smith">Fredrick Smith</td> 
      <td>Ohio</td> 
      <td data-date="03-10">10th Mar</td> 
    </tr> 
  </tbody> 
</table>

解析器- 请注意,此解析器代码仅适用于此修改版本的 tablesorter

// add parser through the tablesorter addParser method 
$(function(){ 

  $.tablesorter.addParser({ 
    // set a unique id 
    id: 'data', 
    is: function(s) { 
      // return false so this parser is not auto detected 
      return false; 
    }, 
    format: function(s, table, cell, cellIndex) { 
      var $cell = $(cell); 
      // I could have used $(cell).data(), then we get back an object which contains both 
      // data-lastname & data-date; but I wanted to make this demo a bit more straight-forward 
      // and easier to understand. 

      // first column (zero-based index) has lastname data attribute 
      if (cellIndex === 0) { 
        // returns lastname data-attribute, or cell text (s) if it doesn't exist 
        return $cell.attr('data-lastname') || s; 

      // third column has date data attribute 
      } else if (cellIndex === 2) { 
        // return "mm-dd" that way we don't need to use "new Date()" to process it 
        return $cell.attr('data-date') || s; 
      } 

      // return cell text, just in case 
      return s; 
    }, 
    // set type, either numeric or text 
    type: 'text' 
  }); 

  $('table').tablesorter({ 
    headers : { 
      0 : { sorter: 'data' }, 
      2 : { sorter: 'data' } 
    }, 
    widgets: ['zebra'] 
  }); 

}); 
于 2012-05-04T16:52:12.423 回答