<!DOCTYPE?html?PUBLIC?"-//W3C//DTD?XHTML?1.0?Transitional//EN"?"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html?xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta?http-equiv="Content-Type"?content="text/html;?charset=utf-8"?/>
<title>9章-22編程練習</title>
<style?type="text/css">
#div1{
width:50%;
float:left;
}
#div2{
float:left;
margin-left:5px;
}
th,td{
width:200px;
text-align:center;
}
</style>
??<script?type="text/javascript">?
??
????window.onload?=?function(){
??changecolor();
?}?
?function?changecolor(){
?var?tbody=document.getElementById("table").lastChild;<!--這里的tbody,不論你寫上或是不寫,默認都是存在的-->
?var?node=tbody.getElementsByTagName("tr");
?for(var?i=1;i<node.length;i++){
?node[i].onmouseover=function(){
?this.style.backgroundColor="#ccc";
?}
?node[i].onmouseout=function(){
?this.style.backgroundColor="#fff";
?}
?}
?}
?????//?鼠標移動改變背景,可以通過給每行綁定鼠標移上事件和鼠標移除事件來改變所在行背景色。
?????????
?????
?????function?add(){
??var?tbody=document.getElementById("table").lastChild;
?var?nextline=document.createElement("tr");
?var?td1=document.createElement("td");
?var?td2=document.createElement("td");
?var?td3=document.createElement("td");
?var?num=tbody.getElementsByTagName('tr');
?if(num.length<=9)
?{
?td1.innerHTML="xh00"+num.length;
?}
else?if(9<num.length<100)
?{
?td1.innerHTML="xh0"+num.length;
?}
else?if(num.length>=100)
?{
?td1.innerHTML="xh"+num.length;
?}
?td2.innerHTML="<input?type='text'?name='名字'?style='font-size:15px;width:200px;text-align:center'>";
?td3.innerHTML="<a?href='javascript:void(0);'?onclick='remove(this)'?>刪除</a>"?;
?nextline.appendChild(td1);
?nextline.appendChild(td2);
?nextline.appendChild(td3);
?tbody.appendChild(nextline);
?changecolor();
?}
??????//?編寫一個函數(shù),供添加按鈕調(diào)用,動態(tài)在表格的最后一行添加子節(jié)點;
?????
?????function?remove(obj){
?var?tbody=document.getElementById("table").lastChild;
?var?del=obj.parentNode.parentNode;
?tbody.removeChild(del);
?var?num=tbody.getElementsByTagName("tr");
?for(var?i=1;i<num.length;i++){
?if(i<=9)
?{
num[i].firstChild.innerHTML="xh00"+i;?
?}
?else?if(10<i<100)
?{
?num[i].firstChild.innerHTML="xh0"+i;?
?}
?}
?}
????
?????//?創(chuàng)建刪除函數(shù)
?????
??</script>?
?</head>?
?<body>?
<div?id="div1">
???<table?border="1"?width="100%"?id="table">
???<tr>
<th>學號</th>
<th>姓名</th>
<th>操作</th>
???</tr>??
???<tr>
<td>xh001</td>
<td>王小明</td>
<td><a?href="javascript:void(0);"?onclick="remove(this)"?>刪除</a></td>???<!--在刪除按鈕上添加點擊事件??-->
???</tr>
???<tr>
<td>xh002</td>
<td>劉小芳</td>
<td><a?href="javascript:void(0);"?onclick="remove(this)"?>刪除</a></td>???<!--在刪除按鈕上添加點擊事件??-->
???</tr>??
???</table>
</div>
<div?id="div2">???
???<input??type="button"?value="添加一行"?onclick="add()"??/>???<!--在添加按鈕上添加點擊事件??-->
</div>???
?</body>
</html>我在用firefox和chrome測試的時候,刪除一行刪不了,點刪除,只把刪除二字去掉了,當前行沒有跟著全刪掉,而我在IE8里測試的時候這個功能可以實現(xiàn),不知道代碼哪個地方出了兼容性錯誤?請好心的大神幫忙看看問題出在哪,感激不盡~!
Javascript進階篇的第9章22節(jié)的編程練習
小三是籃球
2016-07-10 11:36:31