繁体   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