Adding rows and columns to a table dynamically with jQuery

后端 未结 3 1662
囚心锁ツ
囚心锁ツ 2021-01-12 08:55

I have the following JavaScript code:

function addRowToTable()
{
  var tbl = document.getElementById(\'tblSample\');
  var lastRow = tbl.rows.length;
  // if         


        
相关标签:
3条回答
  • 2021-01-12 09:38

    The easiest way is to simply use $('#tblSample').append('<tr> ... </tr>'), manually entering the html string (if it's constant). You can also read the html from somewhere else, for more readable code:

     $('#tblSample').append($('div#blank-row-container').html());
    
    0 讨论(0)
  • 2021-01-12 09:43

    Maybe something like this (but without select): http://jsfiddle.net/dVBMc/3/

    UPDATE: http://jsfiddle.net/dVBMc/6/

    function addRowToTable(table, cell1, cell2) {
        var row;
        row = "<tr><td>" + cell1 + "</td><td>" + cell2 + "</td></tr>";
        table.append(row);
    }
    

    Usage:

    $(document).ready(function() {
        $('button').click(function() {
            addRowToTable($('table'), 'cell1 content', 'cell2 content');
        });
    });
    
    0 讨论(0)
  • 2021-01-12 09:55

    I would avoid using strings of HTML and keep creating DOM elements like you had before. jQuery makes this really easy:

    var row = $("<tr>");
    row.append( $("<td>").text("hello") );
    $("#tblSample").append(row);
    

    See http://api.jquery.com/jQuery/#jQuery2 for more info.

    0 讨论(0)
提交回复
热议问题