【发布时间】:2011-04-04 10:04:54
【问题描述】:
我知道如何使用 jquery 将新行追加或添加到表中:
$('#my_table > tbody:last').append(html);
如何将行(在 html 变量中给出)插入特定的“行索引”i。因此,如果i=3,例如,该行将作为表中的第 4 行插入。
【问题讨论】:
标签: javascript jquery html-table
我知道如何使用 jquery 将新行追加或添加到表中:
$('#my_table > tbody:last').append(html);
如何将行(在 html 变量中给出)插入特定的“行索引”i。因此,如果i=3,例如,该行将作为表中的第 4 行插入。
【问题讨论】:
标签: javascript jquery html-table
要在特定节点(data-tt-id)下添加权限,这对我有用:
var someValue = "blah-id";
$("#tableID > tbody > tr[data-tt-id="' + someValue + '"]').after(row);
【讨论】:
添加到 Nick Craver 的回答并考虑 rossisdead 提出的观点,如果存在必须附加到空表或在某一行之前的情况,我已经这样做了:
var arr = []; //array
if (your condition) {
arr.push(row.id); //push row's id for eg: to the array
idx = arr.sort().indexOf(row.id);
if (idx === 0) {
if (arr.length === 1) { //if array size is only 1 (currently pushed item)
$("#tableID").append(row);
}
else { //if array size more than 1, but index still 0, meaning inserted row must be the first row
$("#tableID tr").eq(idx + 1).before(row);
}
}
else { //if index is greater than 0, meaning inserted row to be after specified index row
$("#tableID tr").eq(idx).after(row);
}
}
希望它可以帮助某人。
【讨论】:
我知道它来晚了,但对于那些想纯粹使用 JavaScript 来实现它的人,你可以这样做:
tr的引用。tr DOM 元素。tr父节点。HTML:
<table>
<tr>
<td>
<button id="0" onclick="addRow()">Expand</button>
</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
</tr>
<tr>
<td>
<button id="1" onclick="addRow()">Expand</button>
</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
</tr>
<tr>
<td>
<button id="2" onclick="addRow()">Expand</button>
</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
</tr>
在 JavaScript 中:
function addRow() {
var evt = event.srcElement.id;
var btn_clicked = document.getElementById(evt);
var tr_referred = btn_clicked.parentNode.parentNode;
var td = document.createElement('td');
td.innerHTML = 'abc';
var tr = document.createElement('tr');
tr.appendChild(td);
tr_referred.parentNode.insertBefore(tr, tr_referred.nextSibling);
return tr;
}
这将在单击按钮的行的正下方添加新的表格行。
【讨论】:
注意:
$('#my_table > tbody:last').append(newRow); // this will add new row inside tbody
$("table#myTable tr").last().after(newRow); // this will add new row outside tbody
//i.e. between thead and tbody
//.before() will also work similar
【讨论】:
试试这个:
$("table#myTable tr").last().after(data);
【讨论】:
$('#my_table tbody tr:nth-child(' + i + ')').after(html);
【讨论】:
试试这个:
var i = 3;
$('#my_table > tbody > tr:eq(' + i + ')').after(html);
或者这个:
var i = 3;
$('#my_table > tbody > tr').eq( i ).after(html);
或者这个:
var i = 4;
$('#my_table > tbody > tr:nth-child(' + i + ')').after(html);
所有这些都会将该行放在相同的位置。 nth-child 使用基于 1 的索引。
【讨论】:
使用eq selector 选择第n 行(从0 开始)并使用after 在其后添加您的行,所以:
$('#my_table > tbody:last tr:eq(2)').after(html);
其中 html 是 tr
【讨论】:
【讨论】:
.before(html)
$($('#my_table > tbody:last')[index]).append(html);
【讨论】: