Use javascript to dynamically add and delete table row table row

Turn: https://blog.csdn.net/summerhmy/article/details/82892271

1, the first and only briefly create a new row in the table there is a button, a delete button.

Figure:

Corresponding html code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
    <title> New Document </title>
    
    <script src="js/editTable.js"  language="javascript"></script>
 </head>
 
 <body>
     <input type="button" value="新增" onclick="createRow()">
     <input type="button" value="删除" onclick="delRow()">
    
     <table id="editTable" border="1" width="800">
         <tr>
            <th>选择</th>
            <th>姓名</th>  </ body>      </ Table>          </ tbody>          <tbody ID = "tbody">          </ TR>             <th> Phone </ TH>
            <th> Gender </ TH>



 



</html>

 

2, and then we write the script javascript dynamically add rows to complete the operation:

function createRow(){
    var editTable=document.getElementById("tbody");
    var tr=document.createElement("tr");
    var td0=document.createElement("td");
    var checkbox=document.createElement("input");
    checkbox.type="checkbox";
    checkbox.name="checkRow";
    td0.appendChild(checkbox);
    var td1=document.createElement("td");
    td1.innerHTML="<input type='text' />";
    var td2=document.createElement("td");
    td2.innerHTML="a2";
    var td3=document.createElement("td");
    td3.innerHTML="a3";
    tr.appendChild(td0);
    tr.appendChild(td1);
    tr.appendChild(td2);
    tr.appendChild(td3);
    editTable.appendChild(tr);
}
 

Creating tr and td elements, increase the line.

Effect:
--------------------- 
 

 

 

3,

Delete button and then write the script javascript

function delRow(){
    var editTable=document.getElementById("tbody");
    if(confirm("确认删除所选?")){
        var checkboxs=document.getElementsByName("checkRow");
        for(var i=0;i<checkboxs.length;i++){
            if(checkboxs[i].checked){
                var n=checkboxs[i].parentNode.parentNode;
                editTable.removeChild(n);
                i--;
            }
        }
        
    }
}
 效果
 

Guess you like

Origin blog.csdn.net/zhaofuqiangmycomm/article/details/93398813