Javascript 使用 jQuery 动态地向表中添加行和列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3479678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:49:44  来源:igfitidea点击:

Adding rows and columns to a table dynamically with jQuery

javascriptjquerydom

提问by user415772

I have the following JavaScript code:

我有以下 JavaScript 代码:

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

How to translate this from DOM calls to jQuery?Can anyone give sample code .

如何将其从 DOM 调用转换为 jQuery?谁能提供示例代码。

回答by cam

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

我会避免使用 HTML 字符串并像以前一样继续创建 DOM 元素。jQuery 让这一切变得非常简单:

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

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

有关更多信息,请参阅http://api.jquery.com/jQuery/#jQuery2

回答by Im0rtality

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

也许是这样的(但没有select):http: //jsfiddle.net/dVBMc/3/

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

更新: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');
    });
});

回答by Ian Henry

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('<tr> ... </tr>'), 手动输入 html 字符串(如果它是常量)。您还可以从其他地方读取 html,以获得更易读的代码:

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