[英]How to add 2 or more rows in table
I have 3 rows, and 3 buttons in same table, I am trying to add new rows independent to each other. 我在同一表格中有3行和3个按钮,我试图添加彼此独立的新行。 But it outputs the first rows while i click second or third button.
但是当我单击第二个或第三个按钮时,它输出第一行。
Here is the javascript code for first button and second button respectively. 这是分别用于第一个按钮和第二个按钮的javascript代码。
function addRow(dataTable, id) {
var table = document.getElementById('dataTable');
var rowCount = table.rows.length;
var row = table.insertRow(3);
var colCount = table.rows[5].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[4].cells[i].innerHTML;
document.getElementById("agri").style.visibility = "hidden"; // remove button from newly added row
}
document.getElementById("agri").style.visibility = "visible";
}
function addRow1(dataTable, id) {
var table = document.getElementById('dataTable');
var rowCount = table.rows.length;
var row = table.insertRow(4);
var colCount = table.rows[6].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[5].cells[i].innerHTML;
document.getElementById("promotion").style.visibility = "hidden"; // remove button from newly added row
}
document.getElementById("promotion").style.visibility = "visible";
}
here is some html 这是一些HTML
<input type="button" id="agri" value="Add Row" onclick="addRow(dataTable,this.id)" />
<input type="button" id="promotion" value="Add Row" onclick="addRow1(dataTable,this.id)" />
Please Help 请帮忙
Thanks 谢谢
You have errors 你有错误
not 不
var table = document.getElementById('dataTable');
but, because I think you use dataTable as variable not string 但是,因为我认为您使用dataTable作为变量而不是字符串
var table = document.getElementById(dataTable);
Also put your html code with table 还把你的HTML代码与表
如何添加row
属性并根据元素编号更改其值
<script>
var ii=0;
function addRow(dataTable, id, type) {
ii++
console.log(id);
var table = document.getElementById(dataTable);
var row = table.insertRow(id+parseInt(type));
var colCount = table.rows[id].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[id].cells[i].innerHTML;
table.rows[id].cells[i].querySelector('input').value=ii.toString();
if(type==1)
table.rows[id].cells[i].style.backgroundColor='red';
else
table.rows[id].cells[i].style.backgroundColor='blue';
}
}
</script>
<table id="dataTable">
<tr>1
<td><input type="button" id="agri" value="Add Row after" onclick="addRow('dataTable',this.parentNode.parentNode.rowIndex,'1')" /></td>
<td><input type="button" id="agri2" value="Add Row before" onclick="addRow('dataTable',this.parentNode.parentNode.rowIndex,'-1')" /></td>
</tr>
</table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.