1、DOM编程
动态 HTML代码加载到浏览器,代码运行后
改变文档(DOM数) 改变结点属性
2、NODE属性
3、NODE常用的方法
4、接下来我们利用DOM编程来做一个动态table案例
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style type="text/css">
.mytb{
border-collapse:collapse;
text-align:center;
width:80%;
}
</style>
<script type="text/javascript">
function check() {
if(document.getElementById("userName").value == "") {
alert("用户名不能为空");
return false;
}
if(document.getElementById("pwd").value == "") {
alert("密码不能为空");
return false;
}
return true;
}
function clearForm() {
document.getElementById("userName").value = "";
document.getElementById("pwd").value = "";
}
function trOnMouseOver() {
this.bgColor = "green";
}
function trOnMouseOut() {
this.bgColor = "white";
}
function saveInfo() {
if(check()) {
var tb = document.getElementById("tb");
var tr = document.createElement("tr");
tr.onmouseover = trOnMouseOver;
tr.onmouseout = trOnMouseOut;
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var td3 = document.createElement("td");
var userName = document.createTextNode(document.getElementById("userName").value);
td1.appendChild(userName);
var pwd = document.createTextNode(document.getElementById("pwd").value);
td2.appendChild(pwd);
var myA = document.createElement("a");
myA.href = "javascript:void(0)";//超链接无效
myA.onclick = deleteRow;
var myAText = document.createTextNode("删除");
myA.appendChild(myAText);
td3.appendChild(myA);
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tb.appendChild(tr);
}
}
function deleteRow() {
var tb = document.getElementById("tb");
var tr =this.parentNode.parentNode;
var userName =tr.firstChild.firstChild.nodeValue;
var ok =confirm("您确定要删除["+userName+"]吗?");
if(ok) {
tb.removeChild(tr);
}
}
</script>
</head>
<body>
<table align="center" >
<caption>DOM编程表格案例</caption>
<tr>
<td>用户名:</td>
<td><input type="text" id="userName" /></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" id="pwd"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="reset" value="清除" onClick="clearForm()"/>
<input type="button" value="注册" "saveInfo()"/>
</td>
</tr>
</table>
<table align="center" border="1" id="tb" class="mytb">
<tr align="center" bgcolor="#999999">
<td width="34%">用户名</td>
<td width="33%">密码</td>
<td>操作</td>
</tr>
</table>
</body>
</html>