gpt4 book ai didi

javascript - 在 HTML 和 Javascript 中添加带有输入的行时重置表输入值

转载 作者:行者123 更新时间:2023-12-01 02:26:01 24 4
gpt4 key购买 nike

我一直在摸不着头脑,不知道为什么我的代码会这样。

我的问题是,为什么当我使用函数 addRow 添加表行时,它会重置前一行的所有输入值?

下面是显示我的问题的代码片段..

function addRow() {
//the html for adding a row (contains the row tag and inputs)
htmlString = '<tr><td><input type="text"></input></td></tr>';
//add the html string to the tbody of the tableTestSamples
document.getElementById("testTable").getElementsByTagName("tbody")[0].innerHTML += htmlString;
}
<table id="testTable">
<tbody>
<tr>
<td>
<input type="text"></input>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input type="button" onclick="addRow()" value="Add Row"></input>
</td>
</tr>
</tfoot>
</table>

它添加了一行..除了重置之前输入的任何值。这是为什么?

谢谢!

最佳答案

问题是您正在改变表格的innerHTML。这会导致浏览器将表的内容视为 HTML 字符串,重新解析 HTML,然后替换表的内容。由于浏览器不会更新 innerHTML 以反射(reflect)输入到输入标记中的值,因此这些值将在此过程中丢失。

为了避免重置输入值,您需要操作 DOM,而不是操作底层源代码。您仍然可以使用 HTML 创建新行,但需要使用如下函数将其添加到表中:appendChild() .

示例:

function addRow() {
var row = document.createElement('tr');
row.innerHTML = '<td><input></td>';

var table = document.getElementById('the-table');
table.appendChild(row);
}
<table id="the-table">
<tr>
<td><input></td>
</tr>
</table>
<button onclick="addRow()">Add Row</button>

关于javascript - 在 HTML 和 Javascript 中添加带有输入的行时重置表输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48794333/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com