Add table row in jQuery

前端 未结 30 2328
既然无缘
既然无缘 2020-11-21 05:40

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

Is this acceptable?

$(\'#myTable\').append(\'

        
30条回答
  •  不思量自难忘°
    2020-11-21 06:28

    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('');
            ($(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','my new row');
    

提交回复
热议问题