2010-08-13 22 views
5

ich den folgenden JavaScript-Code haben:Hinzufügen von Zeilen und Spalten einer Tabelle dynamisch mit jQuery

function addRowToTable() 
{ 
    var tbl = document.getElementById('tblSample'); 
    var lastRow = tbl.rows.length; 
    // if there's no header row in the table, then iteration = lastRow + 1 
    var iteration = lastRow; 
    var row = tbl.insertRow(lastRow); 

    // left cell 
    var cellLeft = row.insertCell(0); 
    var textNode = document.createTextNode(iteration); 
    cellLeft.appendChild(textNode); 

    // right cell 
    var cellRight = row.insertCell(1); 
    var el = document.createElement('input'); 
    el.type = 'text'; 
    el.name = 'txtRow' + iteration; 
    el.id = 'txtRow' + iteration; 
    el.size = 40; 

    el.onkeypress = keyPressTest; 
    cellRight.appendChild(el); 

    // select cell 
    var cellRightSel = row.insertCell(2); 
    var sel = document.createElement('select'); 
    sel.name = 'selRow' + iteration; 
    sel.options[0] = new Option('text zero', 'value0'); 
    sel.options[1] = new Option('text one', 'value1'); 
    cellRightSel.appendChild(sel); 
} 

Wie dies zu übersetzen, von DOM zu jQuery ruft Kann jemand Beispielcode geben?.

Antwort

2

Der einfachste Weg ist, einfach $('#tblSample').append('<tr> ... </tr>') zu verwenden und den HTML-String manuell einzugeben (wenn es konstant ist). Sie können auch den HTML von woanders, für mehr lesbaren Code lesen:

$('#tblSample').append($('div#blank-row-container').html()); 
3

Vielleicht so etwas wie diese (aber ohne 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); 
} 

Verbrauch:

$(document).ready(function() { 
    $('button').click(function() { 
     addRowToTable($('table'), 'cell1 content', 'cell2 content'); 
    }); 
}); 
8

Ich würde es vermeiden, HTML-Strings zu verwenden und weiterhin DOM-Elemente wie zuvor zu erstellen. jQuery macht dies ganz einfach:

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

Siehe http://api.jquery.com/jQuery/#jQuery2 für weitere Informationen.

Verwandte Themen