【发布时间】:2020-01-07 07:34:39
【问题描述】:
简而言之,我需要从表中获取第一列数据,包括附加了 jQuery 的行。
下面是我使用 jQuery 向 HTML 表中添加一行的代码。这一切都按预期工作,但是变量firstColumns(它从表的第一列收集值)不包括额外单击“添加行”按钮所附加的行。
额外的行将需要所有列的数据,包括所有附加的,希望有人知道如何从刷新的 DOM 中获取这些数据?
$(document).ready(function() {
$("#add").on("click", function() {
var firstColumns = [];
$("table#personalPrices tr").each(function() {
var val = $(this).find("th:first").text();
firstColumns.push(val);
});
var existingRow = $('table#personalPrices tbody>tr:nth-child(1)').next('tr');
var newRow = '<tr><td>4 + 23</td><td>test3</td></tr>';
existingRow.after(newRow);
console.log(firstColumns);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="personalPrices">
<tbody>
<tr>
<th>1 + 23</th>
<td>test1</td>
</tr>
<tr>
<th>3 + 23</th>
<td>test2</td>
</tr>
</tbody>
</table>
<button id="add">Add Row</button>
【问题讨论】:
-
您正在使用
<td>添加新行,而填充firstColumns的函数正在寻找<th>。所以你想要这个:var newRow = '<tr><th>4 + 23</th><td>test3</td></tr>';或者你将每个<th>更改为<td>并找到"td:first" -
请在下面查看我的答案。
标签: jquery dom html-table append