Home >Web Front-end >JS Tutorial >Dynamic addition and deletion of table rows based on JavaScript_javascript skills

Dynamic addition and deletion of table rows based on JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:16:491475browse

Another effect of dynamically controlling tables, using JavaScript to dynamically generate table rows and columns, and dynamically delete these columns, rows, etc. After running the code, click the corresponding function button to realize the corresponding table operation function .

1.jsp

<table id="viewTabs">
<thead>
<tr>
<th>产品名称</th>
<th>编号</th>
<th>数量</th>
<th>重量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr>
<td><input name="productName" type="text"></td>
<td><input name="productNumber" type="text"></td>
<td><input name="quantity" type="text"></td>
<td><input name="weight" type="text"></td>
<td></td>
</tr>
</tbody>
</table>
<button type="button" onclick="addTable();" style="margin-left: 750px;">添加行</button>

2.js

//添加行
function addTable(){
var tab=document.getElementById("viewTabs"); //获得表格
var colsNum=tab.rows.item(0).cells.length; //表格的列数
//表格当前的行数 
var num=document.getElementById("viewTabs").rows.length;
var rownum=num;
tab.insertRow(rownum);
for(var i=0;i<4; i++)
{
tab.rows[rownum].insertCell(i);//插入列
if(i==0){
tab.rows[rownum].cells[i].innerHTML=
'<input name="productName" type="text"/>';
}else if(i==1){
tab.rows[rownum].cells[i].innerHTML='<input name="productNumber" type="text"/>';
}else if(i==2){
tab.rows[rownum].cells[i].innerHTML='<input name="quantity" type="text"/>';
}else{
tab.rows[rownum].cells[i].innerHTML='<input name="weight" type="text"/>';
}
}
tab.rows[rownum].insertCell(i);
tab.rows[rownum].cells[i].innerHTML='<a href="#" onclick="delRow(this)">删除行</a>';
}
//删除行
function delRow(obj)
{
var Row=obj.parentNode;
var Row=obj.parentNode; //tr
while(Row.tagName.toLowerCase()!="tr")
{
Row=Row.parentNode;
}
Row.parentNode.removeChild(Row); //删除行
}

The above is the JavaScript implementation shared by the editor to dynamically add and delete table rows. I hope it will be helpful to everyone.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn