Programing Exercise 2017-08-05

xiaoxiao2021-02-28  75

制作一个表格,显示班级的学生信息。 要求: 1. 鼠标移到不同行上时背景色改为色值为 #f2f2f2,移开鼠标时则恢复为原背景色 #fff 2. 点击添加按钮,能动态在最后添加一行

3. 点击删除按钮,则删除当前行

知识预备:

1)JavaScript中的this参数

js中的this变量总是指向调用this的变量。

2) 在table中隐藏了两个标签分别是 <caption></caption> 和<tbody></tbody>,其格式应该为 <table> <caption></caption> <tbody> <tr><td>...<td><tr> <tr><td>...<td><tr> </tbody> </table> 所以定位节点时要注意层级,避免定位错误节点

3) 在编写节点的innerHTML时,可以直接向里面写一个子节点,比如: 

td3.innerHTML="<a href='javascript:;' οnclick='Delet(this)'>删除</a>" ; 但是要注意的是,外面已经使用了双引号,那么内部就只能使用单引号。

代码:

<!DOCTYPE html> <html> <head> <title> new document </title> <meta http-equiv="Content-Type" content="text/html; charset=gbk"/> <script type="text/javascript"> window.οnlοad= function() { height(); } function height(){ var tbody=document.getElementById("table").lastChild; //得到tbody对象,注意是lastChild,因为前面隐藏了一个caption var trs=tbody.getElementsByTagName("tr"); //得到tr(表格行)数组 for(var i=1;i<trs.length;i++) { trs[i].οnmοuseοver=function(){this.style.backgroundColor="#f2f2f2";} //依次绑定onmouseover事件 trs[i].οnmοuseοut=function() { this.style.backgroundColor="#fff";} //依次绑定onmouseout事件, // 鼠标移动改变背景,可以通过给每行绑定鼠标移上事件和鼠标移除事件来改变所在行背景色。 } } function add() { var tbody=document.getElementById("table").lastChild; var newnode=document.createElement("tr"); table.appendChild(newnode); var td1=document.createElement("td"); //创建新行的第一个单元格 td1.innerHTML="<input type='text'/> "; var td2=document.createElement("td"); //创建新行的第二个单元格 td2.innerHTML=" <input type='text'/>"; var td3=document.createElement("td"); td3.innerHTML="<a href='javascript:;' οnclick='Delet(this)'>删除</a>" ; //创建删除单元格,并绑定删除函数 newnode.appendChild(td1); //添加 newnode.appendChild(td2); //添加 newnode.appendChild(td3); //添加 tbody.appendChild(newnode); height(); //添加高亮函数,这样添加后相当于为新加的表行绑定了相应的样式。 }// 编写一个函数,供添加按钮调用,动态在表格的最后一行添加子节点; function Delet(obj) //传入要删除的<tr>中<td>的<a> { var tbody=obj.parentNode.parentNode.parentNode; //找到tbody.即要删除的<tr>的父节点 var tr=obj.parentNode.parentNode; //找到要删除的行(节点) tbidy.removeChild(tr); //父节点.removeChild(待删的子节点) }// 创建删除函数 </script> </head> <body> <table border="1" width="50%" id="table"> <tr> <th>学号</th> <th>姓名</th> <th>操作</th> </tr> <tr> <td>xh001</td> <td>王小明</td> <td><a href="javascript:;" onClick="Delet(this);">删除</a></td> <!--在删除按钮上添加点击事件 --> </tr> <tr> <td>xh002</td> <td>刘小芳</td> <td><a href="javascript:;" onClick="Delet(this);">删除</a></td> <!--在删除按钮上添加点击事件 --> </tr> </table> <input type="button" value="添加一行" onClick="add()" /> <!--在添加按钮上添加点击事件 --> </body> </html>

效果:  

转载请注明原文地址: https://www.6miu.com/read-38348.html

最新回复(0)