Js-动态控制table的tr、td增加及删除的具体实现

时间:2021-12-22 21:09:40
<table id='wifi_clients_table' style="color:#0099CC;font-size:12px;" class="table table-striped table-bordered table-hover table-condensed">
<thead>
<tr class="success">
<th>序号</th>
<th>机器名</th>
<th>IP地址</th>
<th>MAC地址</th>
<th>上行/下行速率</th>
</tr>
</thead>
<tbody> </tbody>
</table>

增加:

if(条件)
{//根据InterfaceType的值区分无线客户端和有限客户端
var table = document.getElementById("wifi_clients_table");
var newRow = table.insertRow(); //创建新行 var newCell1 = newRow.insertCell(0); //创建新单元格
newCell1.innerHTML = "<td>1</td>" ; //单元格内的内容
newCell1.setAttribute("align","center"); //设置位置 var newCell2 = newRow.insertCell(1); //创建新单元格
newCell2.innerHTML = "<td>"+info.LANHosts.HostName+"</td>";
newCell2.setAttribute("align","center"); //设置位置 var newCell3 = newRow.insertCell(2); //创建新单元格
newCell3.innerHTML = "<td>"+info.LANHosts.IPAddress+"</td>";
newCell3.setAttribute("align","center"); //设置位置 var newCell4 = newRow.insertCell(3); //创建新单元格
newCell4.innerHTML = "<td>"+info.LANHosts.MACAddress+"</td>";
newCell4.setAttribute("align","center"); //设置位置 var newCell5 = newRow.insertCell(4); //创建新单元格
newCell5.innerHTML = "<td>"+info.LANHosts.UpRate+"/"+info.LANHosts.DownRate+"kb</td>";
newCell5.setAttribute("align","center"); //设置位置 }

删除:在页面关闭时清除,下次访问时再重新生成,防止每次tr递增,页面错乱

var t1=document.getElementById("lan_clients_table"); 

var rowNum=t1.rows.length;
if(rowNum>0)
{
for(i=0;i<rowNum;i++)
{
t1.deleteRow(i);
rowNum=rowNum-1;
i=i-1;
}
}