How to sort multiple tables with same function by "TableId"?

时间:2019-05-19 04:11:48

标签: javascript html sorttable.js

I'm trying from https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_sort_table_desc but it doesn't work for multiple table.

    <table id="tableData1">
        <tr>
            <th onclick="sortTable(0)">Input Date</th>
            <th onclick="sortTable(1)">Periode</th>
            <th onclick="sortTable(2)">Account</th>
        </tr>
        <tr>
            <td>2019-05-13</td>
            <td>2019-05</td>
            <td>Name A</td>
        </tr>
        <tr>
            <td>2019-04-02</td>
            <td>2019-04</td>
            <td>Name A</td>
        </tr>
        <tr>
            <td>2019-03-02</td>
            <td>2019-03</td>
            <td>Name A</td>
        </tr>
    </table>
    <table id="tableData2">
        <tr>
            <th onclick="sortTable(0)">Input Date</th>
            <th onclick="sortTable(1)">Periode</th>
            <th onclick="sortTable(2)">Account</th>
        </tr>
        <tr>
            <td>2019-05-10</td>
            <td>2019-05</td>
            <td>Name B</td>
        </tr>
        <tr>
            <td>2019-04-01</td>
            <td>2019-04</td>
            <td>Name B</td>
        </tr>
        <tr>
            <td>2019-03-05</td>
            <td>2019-03</td>
            <td>Name B</td>
        </tr>
    </table>

And this is Javascript code:

var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;

table = document.getElementsById("tableData");
switching = true;
dir = "asc"; 
while (switching) {
    switching = false;
    rows = table.getElementsByTagName("TR");
    for (i = 1; i < (rows.length - 1); i++) {
        shouldSwitch = false;
        x = rows[i].getElementsByTagName("TD")[n];
        y = rows[i + 1].getElementsByTagName("TD")[n];
        if (dir == "asc") {
            if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
            shouldSwitch= true;
            break;
            }
        } else if (dir == "desc") {
            if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
                shouldSwitch= true;
                break;
            }
        }
    }
    if (shouldSwitch) {
        rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
        switching = true;
        switchcount ++;      
    } else {
        if (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
        }
    }
}
}

I know why the script doesn't work, this script only for one table not for multiple, buat, can i use this script for multiple tables in same page?

Thank you.

1 个答案:

答案 0 :(得分:0)

您的代码在table = document.getElementsById("tableData");处失败 因为该元素不存在,而是 getElementById (单个元素)。 您可以将代码更改为<th onclick="sortTable('dataTab1e1', 0)">Input Date</th> 然后将功能更改为:

function sortTable(divName, item ) {
   var table = document.getElementById( divName );
....
}