在jQuery中添加表格行

JavaScript

猿小宇宙小哥

2020-03-09

jQuery在表中添加最后一行作为最后一行的最佳方法是什么?

这可以接受吗?

$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');

您可以向这样的表中添加什么内容(例如输入,选择,行数)是否有限制?

第187篇《在jQuery中添加表格行》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
猿蛋蛋凯 2020.03.09
<table id=myTable>
    <tr><td></td></tr>
    <style="height=0px;" tfoot></tfoot>
</table>

You can cache the footer variable and reduce access to DOM (Note: may be it will be better to use a fake row instead of footer).

var footer = $("#mytable tfoot")
footer.before("<tr><td></td></tr>")
阿飞Sam猪猪 2020.03.09

As i have also got a way too add row at last or any specific place so i think i should also share this:

First find out the length or rows:

var r=$("#content_table").length;

and then use below code to add your row:

$("#table_id").eq(r-1).after(row_html);
ㄏ囧囧ㄟ 2020.03.09

当表中没有任何行以及每行都非常复杂时,我将使用这种方式。

style.css:

...
#templateRow {
  display:none;
}
...

xxx.html

...
<tr id="templateRow"> ... </tr>
...

$("#templateRow").clone().removeAttr("id").appendTo( $("#templateRow").parent() );

...
蛋蛋GO 2020.03.09

使用jQuery的“ last()”函数可以轻松完成此操作。

$("#tableId").last().append("<tr><td>New row</td></tr>");
卡卡西Tom 2020.03.09

如果您有a <tbody>和a <tfoot>怎么办?

如:

<table>
    <tbody>
        <tr><td>Foo</td></tr>
    </tbody>
    <tfoot>
        <tr><td>footer information</td></tr>
    </tfoot>
</table>

然后,它将在行脚中插入新行-而不是正文。

因此,最好的解决方案是包含<tbody>标签和用途.append,而不是.after

$("#myTable > tbody").append("<tr><td>row content</td></tr>");

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android