js代码实现表格隔行变色,添加新的元素,以及鼠标停留变色

xiaoxiao2021-03-01  43

js代码实现表格隔行变色,添加新的元素,以及鼠标停留变色

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>隔行变色</title> <script> window.onload=function () { var otab = document.getElementById('tab2'); var oldcolor = ''; for (var i = 0; i < otab.tBodies[0].rows.length; i++) { otab.tBodies[0].rows[i].onmouseover = function () { oldcolor = this.style.background; this.style.background='green'; }; otab.tBodies[0].rows[i].onmouseout = function () { this.style.background=oldcolor; }; if (i%2) { otab.tBodies[0].rows[i].style.background="#CCC"; } else{ otab.tBodies[0].rows[i].style.background=''; } } var obtn = document.getElementById('btn1'); var onumber = document.getElementById('number'); var oname = document.getElementById('name'); var oage = document.getElementById('age'); var oid = otab.tBodies[0].rows.length+1; obtn.onclick = function () { var otr = document.createElement('tr'); var otd = document.createElement('td'); //otd.innerHTML = otab.tBodies[0].rows.length+1; 采用这种方法会让删除的时候出现id重复的情况 otd.innerHTML = oid++; otr.appendChild(otd); var otd = document.createElement('td'); otd.innerHTML = oname.value //? otr.appendChild(otd); var otd = document.createElement('td'); otd.innerHTML = onumber.value //? otr.appendChild(otd); var otd = document.createElement('td'); otd.innerHTML = oage.value //? otr.appendChild(otd); var otd = document.createElement('td'); otd.innerHTML = '<a href="javascript:;">删除</a>' //? otr.appendChild(otd); otd.getElementsByTagName('a')[0].onclick=function () { otab.tBodies[0].removeChild(this.parentNode.parentNode); } otab.tBodies[0].appendChild(otr); }; } </script> </head> <body> 姓名:<input id="name" type="text" /> 学号: <input id="number" type="text" /> 年龄:<input id="age" type="text" /> <input id="btn1" type="button" value="添加" /> <table id="tab2" width="500" border="1"> <thead> <td>序号</td> <td>姓名</td> <td>学号</td> <td>年龄</td> <td>操作</td> </thead> <tbody> <tr> <td>1</td> <td>丁丁</td> <td>131412</td> <td>21</td> <td></td> </tr> <tr> <td>2</td> <td>钟辉</td> <td>131212</td> <td>20</td> <td></td> </tr> <tr> <td>3</td> <td>申振</td> <td>131415</td> <td>23</td> <td></td> </tr> <tr> <td>4</td> <td>郑元超</td> <td>131315</td> <td>21</td> <td></td> </tr> <tr> <td>5</td> <td>于加良</td> <td>111415</td> <td>20</td> <td></td> </tr> </tbody> </table> </body>

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

最新回复(0)