Add table row in jQuery

2018-12-31 00:51发布

What is the best method in jQuery to add an additional row to a table as the last row?

Is this acceptable?

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

Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)?

30条回答
几人难应
2楼-- · 2018-12-31 01:08

My solution:

//Adds a new table row
$.fn.addNewRow = function (rowId) {
    $(this).find('tbody').append('<tr id="' + rowId + '"> </tr>');
};

usage:

$('#Table').addNewRow(id1);
查看更多
不流泪的眼
3楼-- · 2018-12-31 01:12

For the best solution posted here, if there's a nested table on the last row, the new row will be added to the nested table instead of the main table. A quick solution (considering tables with/without tbody and tables with nested tables):

function add_new_row(table, rowcontent) {
    if ($(table).length > 0) {
        if ($(table + ' > tbody').length == 0) $(table).append('<tbody />');
        ($(table + ' > tr').length > 0) ? $(table).children('tbody:last').children('tr:last').append(rowcontent): $(table).children('tbody:last').append(rowcontent);
    }
}

Usage example:

add_new_row('#myTable','<tr><td>my new row</td></tr>');
查看更多
时光乱了年华
4楼-- · 2018-12-31 01:12
<table id="myTable">
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
  <tr>...</tr>
</table>

Write with a javascript function

document.getElementById("myTable").insertRow(-1).innerHTML = '<tr>...</tr><tr>...</tr>';
查看更多
梦寄多情
5楼-- · 2018-12-31 01:12

In a simple way:

$('#yourTableId').append('<tr><td>your data1</td><td>your data2</td><td>your data3</td></tr>');
查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 01:14

I found this AddRow plugin quite useful for managing table rows. Though, Luke's solution would be the best fit if you just need to add a new row.

查看更多
姐姐魅力值爆表
7楼-- · 2018-12-31 01:14

To add a good example on the topic, here is working solution if you need to add a row at specific position.

The extra row is added after the 5th row, or at the end of the table if there are less then 5 rows.

var ninja_row = $('#banner_holder').find('tr');

if( $('#my_table tbody tr').length > 5){
    $('#my_table tbody tr').filter(':nth-child(5)').after(ninja_row);
}else{
    $('#my_table tr:last').after(ninja_row);
}

I put the content on a ready (hidden) container below the table ..so if you(or the designer) have to change it is not required to edit the JS.

<table id="banner_holder" style="display:none;"> 
    <tr>
        <td colspan="3">
            <div class="wide-banner"></div>
        </td>   
    </tr> 
</table>
查看更多
登录 后发表回答