使用JavaScript向表添加行 [英] add rows to table with JavaScript
问题描述
当用户单击添加行"按钮时,我正在尝试使用JavaScript或ASP C#将行添加到表单中的表格中.我有使用JavaScript的工作代码.我想在< td></td>
标记内添加带有文本输入框的行.行计数在我的代码中,因为我正尝试使用它向每个元素添加ID,以备后用.
I am trying to use JavaScript or ASP C# to add rows to a table in form when the user clicks the add row button. I have working code in JavaScript. I want to add the rows with text input boxes inside of the <td></td>
tags. The row count is in my code becasue I am attempting to use it to add IDs to each element for use later.
element.innerHTML(<input id="tagcell"+(rowcount+1)+"" type="text"/>);
function addrow() {
var rowcount =
document.getElementById('tbl').getElementsByTagName('tbody').length;
window.alert(rowcount);
var tableRef = document.getElementById('tbl').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
// Insert a cell in the row at index 0
var tagcell = newRow.insertCell(0);
var desccell = newRow.insertCell(1);
var loccell = newRow.insertCell(2);
var Namecell = newRow.insertCell(3);
var Sigcell = newRow.insertCell(4);
tagcell.innerHTML = "";
desccell.innerHTML="";
loccell.innerHTML = "";
Namecell.innerHTML="";
Sigcell.innerHTML = "";
}
<table id=tbl>
<tr>
<td id=tag_no>Col1</td>
<td id=desc> Col2</td>
<td id=loc> col3</td>
<td id=nme> col4</td>
<td id=sig> col5</td>
</tr>
</table>
<input type="button" value="clickme" onclick="addrow()" />
推荐答案
在这里您可以做到这一点.(显然,您可以根据需要设置文本框的样式.)您的代码添加了行;我只是在每个单元格中添加了 textarea
.
Here's how you could do that. (Obviously you can style the text boxes however you want.) Your code added the rows; I just added a textarea
in each cell.
function addrow() {
var tableRef = document.getElementById('tbl').getElementsByTagName('tbody')[0];
var rowcount = tableRef.rows.length;
window.alert(rowcount);
var newRow = tableRef.insertRow(tableRef.rows.length);
var textBox = "<textarea></textarea>";
// Insert a cell in the row at index 0
var tagcell = newRow.insertCell(0);
var desccell = newRow.insertCell(1);
var loccell = newRow.insertCell(2);
var Namecell = newRow.insertCell(3);
var Sigcell = newRow.insertCell(4);
tagcell.innerHTML = textBox;
desccell.innerHTML= textBox;
loccell.innerHTML = textBox;
Namecell.innerHTML= textBox;
Sigcell.innerHTML = textBox;
}
<table id=tbl>
<tr>
<td id=tag_no>Col1</td>
<td id=desc> Col2</td>
<td id=loc> col3</td>
<td id=nme> col4</td>
<td id=sig> col5</td>
</tr>
</table>
<input type="button" value="clickme" onclick="addrow()" />
编辑:您的行数现在显示正确的数字.(之前每次只显示 1
.)
Your row count shows the correct number now. (It was only showing 1
each time before.)
这篇关于使用JavaScript向表添加行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!