我使用jQuery向表中添加一行作为最后一行。
我是这样做的:
$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
您可以向这样的表中添加的内容(例如输入、选择、行数)是否有限制?有不同的方法吗?
我使用jQuery向表中添加一行作为最后一行。
我是这样做的:
$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
您可以向这样的表中添加的内容(例如输入、选择、行数)是否有限制?有不同的方法吗?
当前回答
尼尔的回答是迄今为止最好的。然而,事情很快就会变得一团糟。我的建议是使用变量来存储元素并将其附加到DOM层次结构中。
HTML
<table id="tableID">
<tbody>
</tbody>
</table>
JAVASCRIPT语言
// Reference to the table body
var body = $("#tableID").find('tbody');
// Create a new row element
var row = $('<tr>');
// Create a new column element
var column = $('<td>');
// Create a new image element
var image = $('<img>');
image.attr('src', 'img.png');
image.text('Image cell');
// Append the image to the column element
column.append(image);
// Append the column to the row element
row.append(column);
// Append the row to the table body
body.append(row);
其他回答
简单来说:
$('#yourTableId').append('<tr><td>your data1</td><td>your data2</td><td>your data3</td></tr>');
使用JQuery添加tabe行:
如果要在表的最后一个子行之后添加行,可以尝试以下操作
$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');
如果要添加表的第1行子级,可以尝试以下操作
$('#myTable tr').after('<tr>...</tr><tr>...</tr>');
jQuery有一个内置的工具,可以随时操作DOM元素。
您可以像这样向表中添加任何内容:
$("#tableID").find('tbody')
.append($('<tr>')
.append($('<td>')
.append($('<img>')
.attr('src', 'img.png')
.text('Image cell')
)
)
);
jQuery中的$(“<some tag>”)是一个标记对象,它可以有几个可以设置和获取的attr属性,以及文本,它表示标记之间的文本:<tag>text</tag>。
这是一些非常奇怪的缩进,但您更容易看到这个示例中的情况。
这可以使用jQuery的“last()”函数轻松完成。
$("#tableId").last().append("<tr><td>New row</td></tr>");
要在当前行的最后一行添加新行,可以使用如下方法
$('#yourtableid tr:last').after('<tr>...</tr><tr>...</tr>');
您可以如上所述追加多行。也可以像这样添加内部数据
$('#yourtableid tr:last').after('<tr><td>your data</td></tr>');
用另一种方式你可以这样做
let table = document.getElementById("tableId");
let row = table.insertRow(1); // pass position where you want to add a new row
//then add cells as you want with index
let cell0 = row.insertCell(0);
let cell1 = row.insertCell(1);
let cell2 = row.insertCell(2);
let cell3 = row.insertCell(3);
//add value to added td cell
cell0.innerHTML = "your td content here";
cell1.innerHTML = "your td content here";
cell2.innerHTML = "your td content here";
cell3.innerHTML = "your td content here";