使用JavaScript添加行并对表格进行排序

5

我遇到了一个非常小的问题,已经花费了两个多小时。

我想要在HTML表格中插入一行,然后按升序排序。我看过这个答案,认为我可以让这个简单的任务工作起来,但是没有成功。

这是我的小表格和表单:

Name: <input type="text" name="name" id="name"><br>
Status: <input type="text" name="status" id="status">><br>
<button onclick="myFunction(document.getElementsByName('name')[0].value,document.getElementsByName('status')[0].value)">Click</button><br><br>
<table id="myTable">
    <thead>
        <tr>
            <th>Name</th>
            <th>Status</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Doe, John</td>
            <td>Approved</td>
        </tr>
        <tr>
            <td>aaa, John</td>
            <td>Approved</td>
        </tr>
    </tbody>
</table>

我的内联JavaScript函数看起来像这样:

function myFunction(name, status) {
    var table = document.getElementById('myTable').getElementsByTagName('tbody')[0];
    var row = table.insertRow(0);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell1.innerHTML = name;
    cell2.innerHTML = status;

    // The following code should sort the table.
    var tbody = $('#mytable').find('tbody');
    tbody.find('tr').sort(function (a, b) {
        return $('td:first', a).text().localeCompare($('td:first', b).text());
    }).appendTo(tbody);
}

请注意,向表格添加一行是可以正常工作的,它只会添加到顶部。
没有控制台错误。显然应该对表格进行排序的代码什么也没做。我在这里分享了我的HTML子集,而且它可以很好地工作。
我知道jQuery tablesorter插件,但不需要使用它。
1个回答

5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接