簡體   English   中英

使用純 Javascript 根據列類名稱對表行進行排序

[英]Sorting table rows based on column class names using pure Javascript

與這個問題非常相似: 根據它們的類名對表行進行排序- 但需要它是純 javascript 而不是 JQuery。

它需要能夠按類名排序。

考慮下表:

<table>
   <thead>
       <th>Column</th>
   </thead>
   <tbody>
       <tr>
           <td class="High">High</td>
       </tr>
       <tr>
           <td class="Medium">Medium</td>
       </tr>
       <tr>
           <td class="Low">Low</td>
       </tr>
   </tbody>
</table>

這些函數需要按特定順序按高、中和低對表格進行排序。

您可以按如下方式執行此操作:

  • 獲取表體的行
  • 根據每行第一列的className對數組進行排序
  • 通過加入結果排序的行元素列表的html內容來更新表體的innerHTML

 const tableBody = document.getElementById("tableBody"); const rows = tableBody.rows; const weights = {"Low":0, "Medium":1, "High":2}; const sortedRows = [...rows].sort((a,b) => weights[a.children[0].className] - weights[b.children[0].className] ); tableBody.innerHTML =[...sortedRows].map(row => row.outerHTML).join("");
 <table> <thead> <th>Column</th> </thead> <tbody id="tableBody"> <tr> <td class="High">High</td> </tr> <tr> <td class="Medium">Medium</td> </tr> <tr> <td class="Low">Low</td> </tr> </tbody> </table>

暫無
暫無

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

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