[英]Sorting HTML table by row data using Javascript
題
給出以下HTML
表
<table id="sort-table">
<tbody>
<tr>
<td>text*1234</td>
<td>data</td>
</tr>
<tr>
<td>text*1224</td>
<td>data</td>
</tr>
<tr>
<td>text*1254</td>
<td>data</td>
</tr>
<tr>
<td>texta*1234</td>
<td>data</td>
</tr>
<tr>
<td>textabc*1234</td>
<td>data</td>
</tr>
<tr>
<td>textab*1234</td>
<td>data</td>
</tr>
<tr>
<td>*2234</td>
<td>data</td>
</tr>
<tr>
<td>textabcd*1234</td>
<td>data</td>
</tr>
<tr>
<td>text*1234</td>
<td>data</td>
</tr>
<tr>
<td>textabc*1234*1234</td>
<td>data</td>
</tr>
</tbody>
</table>
有沒有辦法按照每個<tr>
元素中第一個<td>
元素的值對'sort-table'
表中的行進行排序? 排序應該是每個字母'text'
,然后再通過數字后的值*
。
JQuery
是可用的,但是由vanilla Javascript
組成的答案將是首選。
試圖解決方案
使用以下Javascript我試圖實現難以捉摸的功能。
//get the rows of the table and put them in a NodeList
var tableRows = $("#sort-table")[0].children[0].children;
//create an empty 'tbody' element to replace the old table contents with
var tBody = document.createElement("tbody");
//get the old tbody element to replace it with an empty tbody element
var oldBody = $("#sort-table")[0].children[0];
//get the NodeList as an array
var rowsArray = [].slice.call(tableRows, 1);
//sort the array
rowsArray.sort();
//replace the current table body with an empty one
oldBody.parentNode.replaceChild(tBody, oldBody);
//put each array element in the new table body
rowsArray.forEach(function(entry) {
var tableRef = document.getElementById('sort-table').getElementsByTagName('tbody')[0];
// Insert a row in the table at the last row
var newRow = tableRef.insertRow(tableRef.rows.length);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
newCell.appendChild(entry);
});
這是一個jsfiddle顯示當前如何工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.