首页 > 语言 > JavaScript > 正文

JavaScript获取表格(table)当前行的值、删除行、增加行

2024-05-06 16:22:38
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了JavaScript获取表格(table)当前行的值、删除行、增加行,本文直接给出代码示例,需要的朋友可以参考下

 

 
  1. <html> 
  2. <head> 
  3. <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 
  4. <title>Js获取 table当前行的值</title> 
  5. <script language=javascript> 
  6. var selectedTr = null; 
  7. function c1(obj) { 
  8. obj.style.backgroundColor = 'blue'; //把点到的那一行变希望的颜色;  
  9. if (selectedTr != null) 
  10. selectedTr.style.removeAttribute("backgroundColor"); 
  11. if (selectedTr == obj) 
  12. selectedTr = null;//加上此句,以控制点击变白,再点击反灰  
  13. else 
  14. selectedTr = obj; 
  15. } 
  16. /*得到选中行的第一列的值*/ 
  17. function check() { 
  18. if (selectedTr != null) { 
  19. var str = selectedTr.cells[0].childNodes[0].value; 
  20. document.getElementById("lab").innerHTML = str; 
  21. } else { 
  22. alert("请选择一行"); 
  23. } 
  24. } 
  25. /*删除选中行*/ 
  26. function del() { 
  27. if (selectedTr != null) { 
  28. if (confirm("确定要删除吗?")) { 
  29. alert(selectedTr.cells[0].childNodes[0].value); 
  30. var tbody = selectedTr.parentNode; 
  31. tbody.removeChild(selectedTr); 
  32. } 
  33. } else { 
  34. alert("请选择一行"); 
  35. } 
  36. } 
  37. </script> 
  38. </head> 
  39. <body> 
  40. 单击选中Tr,高亮显示,再单击取消选选中。 
  41. <input type=button value="选中的是哪一行?" onclick="check()"> 
  42. <input type=button value="删除选中行" onclick="del()"> 
  43. <input type=button value="增加一行" onclick="add()"> 
  44. <table width="100%" border="1" cellspacing="0" cellpadding="0" id="tab"> 
  45. <tr onclick="c1(this);" bgcolor="#cccccc"> 
  46. <td><input type="text" value="11"></td> 
  47. <td><input type="text" value="12"></td> 
  48. </tr> 
  49. <tr onclick="c1(this);" bgcolor="#e0e0e0"> 
  50. <td><input type="text" value="21"></td> 
  51. <td><input type="text" value="22"></td> 
  52. </tr> 
  53. <tr onclick="c1(this);" bgcolor="#cccccc"> 
  54. <td><input type="text" value="31"></td> 
  55. <td><input type="text" value="32"></td> 
  56. </tr> 
  57. <tr onclick="c1(this);" bgcolor="#e0e0e0"> 
  58. <td><input type="text" value="41"></td> 
  59. <td><input type="text" value="42"></td> 
  60. </tr> 
  61. <tr onclick="c1(this);" bgcolor="#cccccc"> 
  62. <td><input type="text" value="51"></td> 
  63. <td><input type="text" value="52"></td> 
  64. </tr> 
  65. </table> 
  66. <label id="lab"></label> 
  67. </body> 
  68. </html> 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选