[英]Clicking to add new row in table removing entered data
I have written code that adds a new row in the table when the button is clicked.我编写了在单击按钮时在表中添加新行的代码。 If I enter values and then click the button, the data is deleted.
如果我输入值然后单击按钮,则数据将被删除。 Why?
为什么?
document.getElementById('add').addEventListener('click', function(){ document.querySelector('table tbody').innerHTML += document.querySelector('table tbody tr').innerHTML; });
<button id="add">Add</button> <table> <thead> <tr> <th>1</th> <th>2</th> <th>3</th> <th>4</th> <th>5</th> </tr> </thead> <tbody> <tr> <td><input type="number" placeholder="test" min="1"></td> <td><input type="number" placeholder="test" min="1"></td> <td><input type="number" placeholder="test" min="1"></td> <td><input type="number" placeholder="test" min="1"></td> <td><input type="checkbox" checked></td> </tr> </tbody> </table>
You might want to consider using the append() method.您可能需要考虑使用 append() 方法。
<body>
<button id="add">Add</button>
<table>
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody id="tableBody">
<tr>
<td><input type="number" placeholder="test" min="1"></td>
<td><input type="number" placeholder="test" min="1"></td>
<td><input type="number" placeholder="test" min="1"></td>
<td><input type="number" placeholder="test" min="1"></td>
<td><input type="checkbox" checked></td>
</tr>
</tbody>
</table>
<script>
document.getElementById('add').addEventListener('click', function() {
row = document.createElement('tr');
row.innerHTML = '<td><input type="number" placeholder="test" min="1"></td><td><input type="number" placeholder="test" min="1"></td><td><input type="number" placeholder="test" min="1"></td><td><input type="number" placeholder="test" min="1"></td><td><input type="checkbox" checked></td>'
document.getElementById('tableBody').append(row);
});
</script>
</body>
By doing this, you can add on to the existing content without overwriting it's content.通过这样做,您可以添加到现有内容而不覆盖其内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.