簡體   English   中英

僅使用javaScript按日期值desc按列對HTML中的表進行排序

[英]Sort table in HTML by column with date values desc using only javaScript

是否可以僅使用javaScript而不使用其他任何庫來進行排序?

假設我有一個表,它是第一列,其日期值采用以下格式:MM / dd / yyyy。 該表還有另外兩列,如下所示:

<table id="results" width="360" border="1">
    <thead>
      <tr>
        <th scope="col" width="120">Date Created</th>
        <th scope="col" width="120">Name</th>
        <th scope="col" width="120">Tests</th>
      </tr>
      <tr>
        <td>07/08/2015</td>
        <td>Test Name</td>
        <td>Raven</td>
      </tr>
      <tr>
        <td>05/04/2015</td>
        <td>Test Name 4</td>
        <td>Raven 3</td>
      </tr>
      <tr/>
        <td>01/08/2017</td>
        <td>Test Name 2</td>
        <td>PCT</td>
      </tr>
    </thead>
</table>

可以說添加一個按鈕,並在單擊事件時按“日期”列中的值對行進行排序嗎?

我必須僅使用簡單的javaScript和HTML來完成此操作,因此不幸的是沒有jQuery :(

這是我想給您的一些想法。 顯然,您可以將其擴展為按其他數據類型排序。

我只是通過直接將字符串格式的日期更改為"12/03/2014" 20140312 "12/03/2014"中的20140312格式的八位數字來“欺騙”日期比較-請注意,我假設日期輸入格式為dd/mm/yyyy ,因此,如果出於某種原因您實際上正在使用mm/dd/yyyy ,則必須調整convertDate()函數。

另外,我在表中引入了<tbody>以便可以對數據行進行排序,而完全忽略標題行。

 function convertDate(d) { var p = d.split("/"); return +(p[2]+p[1]+p[0]); } function sortByDate() { var tbody = document.querySelector("#results tbody"); // get trs as array for ease of use var rows = [].slice.call(tbody.querySelectorAll("tr")); rows.sort(function(a,b) { return convertDate(a.cells[0].innerHTML) - convertDate(b.cells[0].innerHTML); }); rows.forEach(function(v) { tbody.appendChild(v); // note that .appendChild() *moves* elements }); } document.querySelector("button").addEventListener("click", sortByDate); 
 <table id="results" width="360" border="1"> <thead> <tr> <th scope="col" width="120">Date Created</th> <th scope="col" width="120">Name</th> <th scope="col" width="120">Tests</th> </tr> </thead> <tbody> <tr> <td>04/04/2015</td> <td>Test Name 2</td> <td>1</td> </tr> <tr> <td>09/08/2017</td> <td>Test Name 5</td> <td>2</td> </tr> <tr> <td>07/08/2015</td> <td>Test Name 4</td> <td>3</td> </tr> <tr> <td>05/04/2015</td> <td>Test Name 3</td> <td>4</td> </tr> <tr> <td>12/08/2017</td> <td>Test Name 6</td> <td>5</td> </tr> <tr> <td>21/03/2014</td> <td>Test Name 1</td> <td>6</td> </tr> </tbody> </table> <button>Sort by date</button> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM