2 回答
TA贡献1934条经验 获得超2个赞
invoiceTableHTML 是相同的,但如果您愿意,可以删除id 。
JS:
function addRow() {
var tbody = document.querySelector("tbody")
tbody.innerHTML +=
'<tr>' +
'<td><div contenteditable></div></td>' +
'<td><div contenteditable></div></td>' +
'<td><div contenteditable></div></td>' +
'<td><div contenteditable></div></td>' +
'<td><div contenteditable></div></td>' +
'<td><div><button type="button" name="button" onclick="addRow()" style="background-color:Transparent; border:none; color:green;"><i class="fas fa-plus-circle"></i></button></div></td>'; +
'</tr>';
}
因为我没有看到循环每个元素的意义,所以我只是直接扩展了新行。+ 按钮仍会在最后创建一行,但其他任何操作都不会。这是想要的吗?
TA贡献1818条经验 获得超3个赞
table.rows.length将选择所有内容rows,包括具有 的行th。相反,仅选择tbody trs.
function addRow() {
var table = document.querySelector("tbody"),
rIndex, cIndex;
for (var i = 0; i < table.rows.length; i++) {
// console.log(table.rows[i].cells);
for (var j = 0; j < table.rows[i].cells.length; j++) {
table.rows[i].cells[j].onclick = function() {
rIndex = this.parentElement.rowIndex + 1;
cIndex = this.cellindex + 1;
document.getElementById("invoiceTable").insertRow(rIndex).innerHTML = '' +
'<tr>' +
'<td><div contenteditable></div></td>' +
'<td><div contenteditable></div></td>' +
'<td><div contenteditable></div></td>' +
'<td><div contenteditable></div></td>' +
'<td><div contenteditable></div></td>' +
'<td><div><button type="button" name="button" onclick="addRow()" style="background-color:Transparent; border:none; color:green;"><i class="fas fa-plus-circle"></i></button></div></td>'; +
'</tr>'
}
}
}
}
<link href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" rel="stylesheet"/>
<main role="main">
<div class="container">
<div class="row">
<div class="col-md-12 mt-5">
<table class="table thead-dark table-hover border-bottom" id="invoiceTable">
<thead>
<tr>
<th style="width: 10%">Item</th>
<th style="width: 50%">Description</th>
<th style="width: 5%">Qty</th>
<th style="width: 10%">Price</th>
<th style="width: 10%">Amount</th>
<th style=>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div contenteditable></div>
</td>
<td>
<div contenteditable></div>
</td>
<td>
<div contenteditable></div>
</td>
<td>
<div contenteditable></div>
</td>
<td>
<div contenteditable></div>
</td>
<td>
<div><button type="button" name="button" onclick="addRow()" style="background-color:Transparent; border:none; color:green;"><i
class="fas fa-plus-circle"></i></button></div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</main>
<!-- /role main -->
- 2 回答
- 0 关注
- 113 浏览
添加回答
举报