我是靠谱客的博主 执着小蝴蝶,这篇文章主要介绍javascript实现表格的添加和删除,现在分享给大家,希望可以做个参考。

注意window.onload()会在网页完成加载后立即执行,我们可以在这个时候为一些元素绑定一些事件响应函数,而一般的函数调用可以写在window.load()函数之外。


代码很简单:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!DOCTYPE html> <html> <head> <title> new document </title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <script type="text/javascript"> window.οnlοad=function(){ // 为每一行绑定onmouseover和onmouseout事件的响应函数 var trs = document.getElementsByTagName("tr"); for(var i=0; i<trs.length; ++i){ trs[i].οnmοuseοver=function(){ this.style.backgroundColor="#f2f2f2"; } trs[i].οnmοuseοut=function(){ this.style.backgroundColor="#fff"; } } //为按钮绑定onclick的响应事件 var btn = document.getElementById("add"); btn.onclick = function(){ var tb = document.getElementById("table"); var tr = document.createElement("tr"); tr.innerHTML = "<tr><td>xh001</td><td>王小明</td><td><a href='javascript:;' οnclick='delrow(this)'>删除</a></td></tr>"; tr.οnmοuseοver=function(){ this.style.backgroundColor="#f2f2f2"; } tr.οnmοuseοut=function(){ this.style.backgroundColor="#fff"; } tb.appendChild(tr); } } //删除某行 function delrow(obj){ var parent = obj.parentNode.parentNode.parentNode; var tr = obj.parentNode.parentNode; parent.removeChild(tr); } </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:;" οnclick="delrow(this)">删除</a></td> <!--在删除按钮上添加点击事件 --> </tr> <tr> <td>xh002</td> <td>刘小芳</td> <td><a href="javascript:;" οnclick="delrow(this)">删除</a></td> <!--在删除按钮上添加点击事件 --> </tr> </table> <script type="text/javascript"> </script> <input id="add" type="button" value="添加一行" /> <!--在添加按钮上添加点击事件 --> </body> </html>


最后

以上就是执着小蝴蝶最近收集整理的关于javascript实现表格的添加和删除的全部内容,更多相关javascript实现表格内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(92)

评论列表共有 0 条评论

立即
投稿
返回
顶部