使用JavaScript制作靈活表單----實現(添加數據、刪除行的操作)


一、使用到的方法:
1. 通過Id獲取元素的方法: document .getElementById(“ ”);
2. 通過TagName獲取元素的方法: document .getElementsByTagName(“ ");
3. 創建元素的方法: document .createElenment(" ");
4. 創建文本節點的方法: document .createTextNode(“ ”)或(對象)
5. 添加子節點的方法: 對象名 . appendChild(對象名)
6. 獲取當前對象父節點的方法: 對象名 .parentNode
注意:如果獲得曾父節點:對象名 . parentNode .parentNode...........
7. 刪除子節點的方法: 父節點名 .removeChild(子節點名)
8. 設置元素的屬性方法: setAttribute(“ 屬性名” , " 屬性值")
9. 元素綁定事件,調函數時,括號里面可以有參數: onclick=" fun(this) "
注意:this指的就是當前對象
 
二、代碼實現
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加</title>
<style>
<!--給表格設置樣式-->
table{
text-align: center;
}
</style>
</head>
<body>
<div>
編號<input type="text" id="No" placeholder="請輸入編號">
姓名<input type="text" id="name" placeholder="請輸入姓名">
性別 <input type="text" id="gender" placeholder="請輸入性別">
<input type="button" id="button" value="添加" onclick="fun()">
</div>
<table border="1" cellspacing="0" width="640px">
<tr>
<th colspan="4">學生信息</th>
 
</tr>
<tr>
<!--這里使用th可以使文字變大、變粗-->
<th>編號</th>
<th>姓名</th>
<th>性別</th>
<th>操作</th>
</tr>
</table>
 
<script>
<!--首先要給添加按鈕綁定事件-->
function fun(){
//第一步,要獲取用戶已輸入的值
var No=document.getElementById("No").value;
var name=document.getElementById("name").value;
var gender=document.getElementById("gender").value;
//第二步:
// 1.添加 td-No列
var td_No=document.createElement("td");
//添加文本節點
var text_No=document.createTextNode(No);
//在列中添加文本節點
td_No.appendChild(text_No);
//2.添加td_name列
var td_name=document.createElement("td");
//添加文本節點
var text_name=document.createTextNode(name);
//把文本節點添加到列中
td_name.appendChild(text_name);
//3.添加td_gender列
var td_gender=document.createElement("td");
//添加文本節點
var text_gender=document.createTextNode(gender);
//把文本節點添加到列中
td_gender.appendChild(text_gender);
//4.添加td_a列
var td_a=document.createElement("td");
var a=document.createElement("a");
//設置額a標簽的屬性
a.setAttribute("href","#");
a.setAttribute("id","a");
a.setAttribute("onclick","del()");//this指的是獲得當前對象
//添加文本節點
var text=document.createTextNode("刪除");
//把文本節點添加到a標簽中
a.appendChild(text);
//把a標簽添加到列中
td_a.appendChild(a);
//第三步:添加行
var tr=document.createElement("tr");
//第四部把列添加到行中去
tr.appendChild(td_No);
tr.appendChild(td_name);
tr.appendChild(td_gender);
tr.appendChild(td_a);
//第五步:把行添加到表格中
var table=document.getElementsByTagName("table")[0];
table.appendChild(tr);
}
//刪除
function del(){
//獲取當前對象
var j=document.getElementById("a");
//獲取當前對象所在的表
var table=j.parentNode.parentNode.parentNode;
//獲取當前對象所在的行
var tr=j.parentNode.parentNode;
//執行刪除操作
table.removeChild(tr);
}
 
</script>
</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM