【问题标题】:Table input values resetting when adding rows with inputs in HTML and Javascript在 HTML 和 Javascript 中添加带有输入的行时重置表输入值
【发布时间】: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


【解决方案1】:

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

为避免重置输入值,您需要操作 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>

【讨论】:

    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 2019-04-08
    • 2021-12-19
    相关资源
    最近更新 更多