Learning to add and delete rows in table with JS

          In recent days, I have completed the study of DOM and DOM nodes, node objects, Element objects, and Attribute objects in JS. DOM is the interface for Javascript to operate web pages, the full name is Document Object Model (Document Object Model). Its function is to convert a web page into a Javascript object, so that various operations (such as adding and deleting elements, etc.) can be performed with Javascript scripts.

       Today's homework is to make a table that can directly add rows to the table through input, add a delete button in the remarks column of each row of the table, and click the delete button to delete the row directly. It is a simple application of the learned node:

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dom练习</title>
</head>
<body>
姓名:<input type="text" id="name" />
联系方式:<input type="text" id="email" />
年龄:<input type="text" id="age"/>
<input type="button" value="添加用户" onclick="addLine()"/><br>
<br /><br /><hr /><br />
<table id="userTable" align="center" border=1 cellspacing=0 cellpadding=5 width="50%">
    <tr>
        <th>姓名</th>
        <th>联系方式</th>
        <th>年龄</th>
        <th>操作</th>
    </tr>
    <tr>
        <td>xiaowang</td>
        <td>[email protected]</td>
        <td>15</td>
        <td>
            <input type="button" value="删除" onclick="delLine(this)" />
        </td>
    </tr>


</table>




<script>
function addLine(){
var name=document.getElementById('name');
var namevalue=name.value;
var email=document.getElementById('email');
var emailvalue=email.value;
var age=document.getElementById('age')
var agevalue=age.value;
var table=document.getElementById('userTable');
var addrow='<tr><td>'+namevalue+'</td><td>'+emailvalue+'</td><td>'+agevalue+'</td><td> <input type="button" value="删除" onclick="delLine(this)" /></td></tr>';
var oldrow=table.innerHTML;
var addrow=oldrow+addrow;table.innerHTML=addrow;

}
function delLine(ob){
var deltr=ob.parentNode.parentNode;
var table=deltr.parentNode;
table.removeChild(deltr);
}
</script>
</body>
</html>

   

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326071390&siteId=291194637