【发布时间】:2018-02-14 18:56:41
【问题描述】:
我一直在摸不着头脑,为什么我的代码会这样运行。
我的问题是,为什么当我使用函数 addRow 添加表行时,它会重置前行的所有输入值?
下面是一个代码 sn-p 显示我的问题..
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会导致它替换所有现有的子元素。尝试改用appendChild()。
标签: javascript jquery html html-table