繁体   English   中英

如何通过HTML中的用户输入在表中添加新行

[英]How to add new row in table from user input in HTML

我只想建立一个网站。 它有一个表,显示每行的数据。 基本上,当用户单击添加按钮时,此表必须能够添加包含新数据的新行。

这是我的代码:

 function myFunction() { var table = document.getElementById("myTable"); var row = table.insertRow(0); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); cell1.innerHTML = "NEW CELL1"; cell2.innerHTML = "NEW CELL2"; } 
 table, td { border: 1px solid black; } 
 <p>Click the button to add a new row at the first position of the table and then add cells and content.</p> <table id="myTable"> <tr> <td>Row1 cell1</td> <td>Row1 cell2</td> </tr> <tr> <td>Row2 cell1</td> <td>Row2 cell2</td> </tr> <tr> <td>Row3 cell1</td> <td>Row3 cell2</td> </tr> </table> <br> <button onclick="myFunction()">Try it</button> 

但是该代码的结果是,当用户单击添加按钮时,它始终显示“ NEW CELL 1”和“ NEW CELL 2”。 我的问题是,如何修改代码,尤其是:

cell1.innerHTML = "NEW CELL1";
        cell2.innerHTML = "NEW CELL2";

这样,该表就可以从用户那里获取输入数据了?

只需获取您的输入值并将其设置为目标单元格的html值

 function myFunction() { var table = document.getElementById("myTable"); var row = table.insertRow(0); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); cell1.innerHTML = document.getElementById('cellOne').value; cell2.innerHTML = document.getElementById('cellTwo').value; } 
 table, td { border: 1px solid black; } 
 <p>Click the button to add a new row at the first position of the table and then add cells and content.</p> <table id="myTable"> <tr> <td>Row1 cell1</td> <td>Row1 cell2</td> </tr> <tr> <td>Row2 cell1</td> <td>Row2 cell2</td> </tr> <tr> <td>Row3 cell1</td> <td>Row3 cell2</td> </tr> </table> <br> <input type='text' id='cellOne' /> <input type='text' id='cellTwo' /> <button onclick="myFunction()">Try it</button> 

您需要一些表单输入来输入文本,这是一个非常基本的示例,可以帮助您入门:

 function myFunction() { var table = document.getElementById("myTable"); var row = table.insertRow(0); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); cell1.innerHTML = document.querySelector('#newCellOneText').value; cell2.innerHTML = document.querySelector('#newCellTwoText').value; } 
 table, td { border: 1px solid black; } 
 <p>Click the button to add a new row at the first position of the table and then add cells and content.</p> <table id="myTable"> <tr> <td>Row1 cell1</td> <td>Row1 cell2</td> </tr> <tr> <td>Row2 cell1</td> <td>Row2 cell2</td> </tr> <tr> <td>Row3 cell1</td> <td>Row3 cell2</td> </tr> </table> <br> Cell 1 Text: <input type="text" id="newCellOneText" /><br/> Cell 2 Text: <input type="text" id="newCellTwoText" /><br/> <button onclick="myFunction()">Try it</button> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM