JS动态添加行数,方便修改列数,重用度比较高的代码。(最好带上删除行方法,从下到上删除)
发布网友
发布时间:2022-05-31 21:36
我来回答
共1个回答
热心网友
时间:2023-10-30 03:25
<script type='text/javascript'>
function addRows(table,cols,rows,data){
table=table.firstChild; /*对tbody进行操作*/
var tr,td;
for(var i=0;i<rows;i++){
tr=document.createElement('TR');
for(var x=0;x<cols;x++){
td=document.createElement('TD');
td.innerText=data[i][x];
tr.appendChild(td);
}
table.appendChild(tr);
}
}
function delRows(table,rows){
table=table.firstChild;
for(var i=0;i<rows;i++){
if(table.lastChild){
table.removeChild(table.lastChild);
}else{
return ;
}
}
}
</script>
</head>
<body>
<!-- 下边是测试代码 -->
<button onclick='addRows(tble,5,4,[["1","2","3","4","5"],["7","8","9","10","11"],["12","13","14","15","16"],["21","22","23","24","25"]]);'>addRows</button>
<button onclick='delRows(tble,3);'>delRows</button>
<table id='tble'>
<tbody>
<tr>
<td>啊大哥啊</td>
<td>啊大哥啊</td>
<td>啊大哥啊</td>
<td>啊大哥啊</td>
<td>啊大哥啊</td>
</tr>
<tr>
<td>啊大哥啊</td>
<td>啊大哥啊</td>
<td>啊大哥啊</td>
<td>啊大哥啊</td>
<td>啊大哥啊</td>
</tr>
<tr>
<td>啊大哥啊</td>
<td>啊大哥啊</td>
<td>啊大哥啊</td>
<td>啊大哥啊</td>
<td>啊大哥啊</td>
</tr>
</tbody>
</table>