簡體   English   中英

使用Javascript按行數據對表進行排序

[英]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顯示當前如何工作

您可以使用sort()方法將行組織為所需的順序:

$('#sort-table tr').sort(function(a, b) {
    var aText = $(a).find('td:eq(0)').text();
    var bText = $(b).find('td:eq(0)').text();

    if (aText > bText)
        return 1;
    else if (aText < bText)
        return -1;
    return 0;
}).appendTo('#sort-table');

更新的例子

暫無
暫無

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

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