J'ai le code JavaScript suivant:
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);
}
3 Réponses :
Le moyen le plus simple consiste simplement à utiliser $ ('# tblsample'). Ajoutez (' ... tr>') code>, entrant manuellement sur la chaîne HTML (si elle est constante ). Vous pouvez également lire le code HTML de quelque part ailleurs, pour un code plus lisible: $('#tblSample').append($('div#blank-row-container').html());
Peut-être quelque chose comme ceci (mais sans mise à jour:
http://jsfiddle.net/dvbmc/6/ p> Utilisation: P> Sélectionnez code>): http: // jsfiddle .NET / DVBMC / 3 / $(document).ready(function() {
$('button').click(function() {
addRowToTable($('table'), 'cell1 content', 'cell2 content');
});
});
J'éviterais d'utiliser des chaînes de HTML et continuez à créer des éléments DOM comme vous l'avez auparavant. JQuery fait cela vraiment simple: voir http: // API. jquery.com/jQuery/#jquery2 Pour plus d'informations. P> P>