7
votes

Ajout de lignes et de colonnes à une table de manière dynamique avec jQuery

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);
}


0 commentaires

3 Réponses :


2
votes

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());


0 commentaires

3
votes

Peut-être quelque chose comme ceci (mais sans Sélectionnez code>): http: // jsfiddle .NET / DVBMC / 3 /

mise à jour: http://jsfiddle.net/dvbmc/6/ p> xxx

Utilisation: P>

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


0 commentaires

9
votes

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: xxx

voir http: // API. jquery.com/jQuery/#jquery2 Pour plus d'informations.


0 commentaires