我有一个包含 2 列和 1 行的表格。当用户单击“添加新行”按钮时,我希望它生成另一行带有一组干净的输入。
当前的 HTML 表格:
<table class="table table-bordered">
<thead>
<tr>
<th>Description</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr>
<td><textarea rows="5" cols="1" placeholder="Enter task description here..."></textarea></td>
<td><input type="file" onchange="previewFile()"><img src="" height="80"></td><br>
</tr>
</tbody>
</table>
<input type="button" value="Add new row">
最佳答案
非常简单。您可以使用 insertAdjacentHTML
function addNewRow() {
let tds = document.getElementsByTagName("td");
tds[tds.length - 2].insertAdjacentHTML('afterend', '<td><textarea rows="5" cols="1" placeholder="Enter task description here..."></textarea></td>')
}
<table class="table table-bordered">
<thead>
<tr>
<th>Description</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr>
<td><textarea rows="5" cols="1" placeholder="Enter task description here..."></textarea></td>
<td><input type="file" onchange="previewFile()"><img src="" height="80"></td><br>
</tr>
</tbody>
</table>
<input type="button" value="Add new row" onclick="addNewRow()">
增加占位符:
let i = 1;
function addNewRow() {
i++;
let tds = document.getElementsByTagName("td");
tds[tds.length - 2].insertAdjacentHTML('afterend', `<td><textarea rows="5" cols="1" placeholder="Enter task description here #${i}"></textarea></td>`)
}
<table class="table table-bordered">
<thead>
<tr>
<th>Description</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr>
<td><textarea rows="5" cols="1" placeholder="Enter task description here #1"></textarea></td>
<td><input type="file" onchange="previewFile()"><img src="" height="80"></td><br>
</tr>
</tbody>
</table>
<input type="button" value="Add new row" onclick="addNewRow()">
jQuery 解决方案:
function addNewRow() {
$("td").eq($("td").length - 2).after('<td><textarea rows="5" cols="1" placeholder="Enter task description here..."></textarea></td>');
}
<table class="table table-bordered">
<thead>
<tr>
<th>Description</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr>
<td><textarea rows="5" cols="1" placeholder="Enter task description here..."></textarea></td>
<td><input type="file" onchange="previewFile()"><img src="" height="80"></td><br>
</tr>
</tbody>
</table>
<input type="button" value="Add new row" onclick="addNewRow()">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
关于javascript - 如何使用 onClick 事件生成新的表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57346791/