复制表格行添加输入框时输入值重置问题求助
问题:添加表格行时输入框值被重置
点击按钮复制表格行以添加新输入行时,所有已填写的输入框值都会被重置。现有代码如下:
<div style="margin-left: 2em;margin-right: 2em;"> <table class="table table-bordered"> <thead> <tr> <!-- th`s --> </tr> </thead> <tbody id="aditional"> <tr id="template"> <!-- inputs and blank td`s --> </tr> <script> const temp = document.getElementById("template").innerHTML; const adit = document.getElementById("aditional"); function add() { adit.innerHTML+='<tr>'+temp+'</tr>'; renum(); } function renum() { const lp = document.getElementsByClassName("lp"); for(let i=0;i<lp.length;i++) { lp[i].innerHTML = i+1; } } </script> </tbody> </table> <button class="btn btn-success" type="button" onclick="add()">Dodaj</button> </div>
也曾尝试将模板innerHTML转为字符串:
const temp = (document.getElementById("template").innerHTML).toString()
但问题依旧。
原因分析
使用adit.innerHTML += ...修改DOM时,浏览器会重新解析整个<tbody>的HTML内容。原有输入框的用户输入值属于动态状态,不会被包含在初始的innerHTML字符串中,因此重新渲染后所有输入框会回到初始空值状态。
解决方案
改用DOM节点克隆的方式添加新行,避免重新渲染整个tbody,从而保留现有输入框的值:
修改后的完整代码
<div style="margin-left: 2em;margin-right: 2em;"> <table class="table table-bordered"> <thead> <tr> <!-- th`s --> </tr> </thead> <tbody id="aditional"> <!-- 初始行可按需保留 --> </tbody> </table> <!-- 模板行隐藏,不参与页面渲染 --> <tr id="template" style="display:none;"> <!-- inputs and blank td`s --> </tr> <button class="btn btn-success" type="button" onclick="add()">Dodaj</button> <script> const templateRow = document.getElementById("template"); const adit = document.getElementById("aditional"); function add() { // 深度克隆模板行,包含所有子元素 const newRow = templateRow.cloneNode(true); // 移除隐藏样式,确保新行正常显示 newRow.style.display = ""; // 移除模板id,避免页面出现重复id newRow.removeAttribute("id"); adit.appendChild(newRow); renum(); } function renum() { const lp = document.getElementsByClassName("lp"); for(let i=0;i<lp.length;i++) { lp[i].innerHTML = i+1; } } </script> </div>
关键修改点
- 将模板行移到
<tbody>外部并隐藏,避免被当作实际行渲染。 - 使用
cloneNode(true)深度克隆模板行,复制完整DOM结构的同时不影响现有行状态。 - 克隆后移除模板的id和隐藏样式,保证新行正常显示且无重复id。
这种方式只会在tbody末尾添加新的DOM节点,不会重新渲染现有内容,已填写的输入框值会被完整保留。
内容的提问来源于stack exchange,提问作者user23020267
相关产品推荐
相关产品推荐

