在表的第一行上方添加新行

时间:2013-08-16 09:29:38

标签: javascript jquery dom

我有一个包含12列的表格。每列都有一个文本框。 When I click on an 'Add' button, a new row should be inserted above the first row of the table。我该怎么办?比方说,如果我使用jquery append(),它只会在末尾添加行,但我想在第一行的顶部添加。

7 个答案:

答案 0 :(得分:5)

尝试

$("#tableId tbody").prepend("<tr>..</tr>");

答案 1 :(得分:3)

您可以使用以下替代方案

1) .before()用于文件click here
2) .insertBefore()用于文档click here
3) .prepend()用于文档click here

答案 2 :(得分:2)

Vanilla JavaScript中,它真的很简单:

var firstRow = yourTable.rows[0];
firstRow.parentNode.insertBefore(newRow,firstRow);

答案 3 :(得分:1)

使用.prepend

$("#tableId tbody").prepend("tr code here");

答案 4 :(得分:0)

您可以使用以下内容:

$('table > tbody > tr:first').before('<tr>...</tr>');

答案 5 :(得分:0)

使用.prepend()方法。此功能完全符合您的需要。

答案 6 :(得分:0)

试试这个:

<table id="tblTest">
    <tr>
        <td><input type="text"/></td>
        <td><input type="text"/></td>
        <td><input type="text"/></td>
        <td><input type="text"/></td>
        <td><input type="text"/></td>
        <td><input type="text"/></td>
        <td><input type="text"/></td>
        <td><input type="text"/></td>
        <td><input type="text"/></td>
        <td><input type="text"/></td>
        <td><input type="text"/></td>
        <td><input type="text"/></td>
    </tr>
</table>
<table>
    <tr>
        <td><input type="button" value="Add" id="btnAdd"></input></td>
    </tr>
</table>


var row = $("#tblTest tbody").html();
$("#btnAdd").click(function(){
    $("#tblTest tbody").prepend(row);
});

Fiddle