Add table row in jQuery

前端 未结 30 2257
既然无缘
既然无缘 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:17

    Neil's answer is by far the best one. However things get messy really fast. My suggestion would be to use variables to store elements and append them to the DOM hierarchy.

    HTML

    JAVASCRIPT

    // Reference to the table body
    var body = $("#tableID").find('tbody');
    
    // Create a new row element
    var row = $('');
    
    // Create a new column element
    var column = $('');
    
    // Create a new image element
    var image = $('');
    image.attr('src', 'img.png');
    image.text('Image cell');
    
    // Append the image to the column element
    column.append(image);
    // Append the column to the row element
    row.append(column);
    // Append the row to the table body
    body.append(row);
    

提交回复
热议问题