【问题标题】:Sorting table rows based on column class names using pure Javascript使用纯Javascript根据列类名对表行进行排序
【发布时间】:2020-11-02 03:10:50
【问题描述】:

与这个问题非常相似:Sort table rows based on their Class Names - 但需要它使用纯 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>

函数需要按特定顺序按高、中、低对表格进行排序。

【问题讨论】:

标签: javascript


【解决方案1】:

你可以这样做:

  • 获取表体的行数
  • 根据每行第一列的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>

【讨论】:

  • 完美,谢谢。没有 tbody 有没有办法做到这一点?如果我没有 tbody,我可以用表 id 替换它吗?
  • @Matthew98 不客气,是的,您可以将id 设置为table,但在这种情况下,它也会占用标题行。
猜你喜欢
  • 2016-11-16
  • 1970-01-01
  • 2014-07-24
  • 2015-10-02
  • 1970-01-01
  • 2021-08-04
  • 2019-12-23
  • 2012-09-29
  • 2015-01-08
相关资源
最近更新 更多