我只想建立一个网站。它有一个表,显示每行的数据。基本上,当用户单击添加按钮时,该表必须能够添加包含新数据的新行。
这是我的代码:
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";
这样,该表就可以从用户那里获取输入数据了吗?
答案 0 :(得分:3)
只需获取您的输入值并将其设置为目标单元格的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>
答案 1 :(得分:2)
您需要一些表单输入来输入文本,这是一个非常基本的示例,供您入门:
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>