当前位置:   article > 正文

js实现动态添加删除表格数据的两种方式_js动态添加表格内容

js动态添加表格内容

目录

1、通过创建节点实现

css代码

html代码

js代码

完整代码

2、通过渲染表格,事件委托实现

css代码

html代码

js代码

完整代码

效果图


1、通过创建节点实现

思路:先把整体的html结构写出来,table表格分为3部分,其中tbody中的内容通过节点创建出来,删除时,找到其祖先元素的节点进行remove(),表单内的各个框的值对应表格的内容。

css代码

  1. <style>
  2. .wrapper {
  3. display: flex;
  4. margin-left: 100px;
  5. margin-top: 100px;
  6. }
  7. .box {
  8. width: 300px;
  9. height: 400px;
  10. /* border: 2px solid red; */
  11. margin-left: 50px;
  12. }
  13. input {
  14. height: 40px;
  15. width: 200px;
  16. margin-bottom: 30px;
  17. }
  18. button {
  19. background-color: #23669a;
  20. color: white;
  21. width: 50px;
  22. height: 30px;
  23. border-radius: 5px;
  24. outline: none;
  25. border: none;
  26. margin-left: 50px;
  27. }
  28. table {
  29. border: 1px solid #dbdbdb;
  30. border-collapse: collapse;
  31. }
  32. table tr,
  33. th,
  34. td {
  35. height: 50px;
  36. width: 180px;
  37. border: 1px solid #dbdbdb;
  38. text-align: center;
  39. }
  40. thead tr {
  41. background-color: #f4f4f5;
  42. }
  43. tbody tr td:nth-child(3) {
  44. color: #f54d7b;
  45. }
  46. </style>

html代码

  1. <div class="wrapper">
  2. <div>
  3. <table>
  4. <thead>
  5. <th>姓名</th>
  6. <th>科目</th>
  7. <th>成绩</th>
  8. <th>操作</th>
  9. </thead>
  10. <tbody>
  11. </tbody>
  12. <tfoot>
  13. <tr>
  14. <td colspan="4"> 总分:<span class="total"></span>平均分: <span class="avg"></span></td>
  15. </tr>
  16. </tfoot>
  17. </table>
  18. </div>
  19. <div class="box">
  20. 姓名:<input type="text" placeholder="请输入姓名" class="name"><br>
  21. 科目:<input type="text" placeholder="请输入科目" class="sub"><br>
  22. 分数:<input type="text" placeholder="请输入分数" class="score"><br>
  23. <button>添加</button>
  24. </div>
  25. </div>

js代码

  1. <script>
  2. //获取元素
  3. const tbody = document.querySelector('tbody')
  4. const btn = document.querySelector('button')
  5. const name = document.querySelector('.name')
  6. const sub = document.querySelector('.sub')
  7. const score = document.querySelector('.score')
  8. let total = document.querySelector('.total')
  9. let avg = document.querySelector('.avg')
  10. //给按钮添加点击事件
  11. btn.addEventListener('click', function () {
  12. //创建元素
  13. const tr = document.createElement('tr')
  14. const td1 = document.createElement('td')
  15. const td2 = document.createElement('td')
  16. const td3 = document.createElement('td')
  17. const td4 = document.createElement('td')
  18. if(name.value===''||sub.value===''||score.value===''){
  19. alert('姓名,科目,成绩不能为空')
  20. }else{
  21. td1.innerHTML = name.value
  22. td2.innerHTML = sub.value
  23. td3.innerHTML = score.value
  24. td4.innerHTML = '<a href="javascript:;">删除</a>'
  25. tr.appendChild(td1)
  26. tr.appendChild(td2)
  27. tr.appendChild(td3)
  28. tr.appendChild(td4)
  29. tbody.appendChild(tr)
  30. name.value = ''
  31. sub.value = ''
  32. score.value = ''
  33. }
  34. let three1 = document.querySelectorAll('tbody tr td:nth-child(3)')
  35. let sum = 0
  36. for (let j = 0; j < three1.length; j++) {
  37. sum += (three1[j].innerHTML - 0)
  38. }
  39. //总分
  40. total.innerHTML = `${sum}`
  41. //平均值
  42. avg.innerHTML = `${sum / three1.length}`
  43. //给创建的a添加删除的点击事件
  44. let as = document.querySelectorAll('a')
  45. for (let i = 0; i < as.length; i++) {
  46. as[i].addEventListener('click', function () {
  47. // tbody.removeChild(this.parentNode.parentNode)
  48. sum -= (three1[i].innerHTML - 0)
  49. this.parentNode.parentNode.remove()
  50. total.innerHTML = `${sum}`
  51. // total.innerHTML = `${sum - (three1[i].innerHTML - 0)}`
  52. let three = document.querySelectorAll('tbody tr td:nth-child(3)')
  53. avg.innerHTML = `${(sum / three.length).toFixed(2) === 'NaN' ? 0 : (sum / three.length).toFixed(2)}`
  54. })
  55. }
  56. })
  57. </script>

完整代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <style>
  8. .wrapper {
  9. display: flex;
  10. margin-left: 100px;
  11. margin-top: 100px;
  12. }
  13. .box {
  14. width: 300px;
  15. height: 400px;
  16. /* border: 2px solid red; */
  17. margin-left: 50px;
  18. }
  19. input {
  20. height: 40px;
  21. width: 200px;
  22. margin-bottom: 30px;
  23. }
  24. button {
  25. background-color: #23669a;
  26. color: white;
  27. width: 50px;
  28. height: 30px;
  29. border-radius: 5px;
  30. outline: none;
  31. border: none;
  32. margin-left: 50px;
  33. }
  34. table {
  35. border: 1px solid #dbdbdb;
  36. border-collapse: collapse;
  37. }
  38. table tr,
  39. th,
  40. td {
  41. height: 50px;
  42. width: 180px;
  43. border: 1px solid #dbdbdb;
  44. text-align: center;
  45. }
  46. thead tr {
  47. background-color: #f4f4f5;
  48. }
  49. tbody tr td:nth-child(3) {
  50. color: #f54d7b;
  51. }
  52. </style>
  53. </head>
  54. <body>
  55. <div class="wrapper">
  56. <div>
  57. <table>
  58. <thead>
  59. <th>姓名</th>
  60. <th>科目</th>
  61. <th>成绩</th>
  62. <th>操作</th>
  63. </thead>
  64. <tbody>
  65. </tbody>
  66. <tfoot>
  67. <tr>
  68. <td colspan="4"> 总分:<span class="total"></span>平均分: <span class="avg"></span></td>
  69. </tr>
  70. </tfoot>
  71. </table>
  72. </div>
  73. <div class="box">
  74. 姓名:<input type="text" placeholder="请输入姓名" class="name"><br>
  75. 科目:<input type="text" placeholder="请输入科目" class="sub"><br>
  76. 分数:<input type="text" placeholder="请输入分数" class="score"><br>
  77. <button>添加</button>
  78. </div>
  79. </div>
  80. <script>
  81. //获取元素
  82. const tbody = document.querySelector('tbody')
  83. const btn = document.querySelector('button')
  84. const name = document.querySelector('.name')
  85. const sub = document.querySelector('.sub')
  86. const score = document.querySelector('.score')
  87. let total = document.querySelector('.total')
  88. let avg = document.querySelector('.avg')
  89. //给按钮添加点击事件
  90. btn.addEventListener('click', function () {
  91. //创建元素
  92. const tr = document.createElement('tr')
  93. const td1 = document.createElement('td')
  94. const td2 = document.createElement('td')
  95. const td3 = document.createElement('td')
  96. const td4 = document.createElement('td')
  97. if(name.value===''||sub.value===''||score.value===''){
  98. alert('姓名,科目,成绩不能为空')
  99. }else{
  100. td1.innerHTML = name.value
  101. td2.innerHTML = sub.value
  102. td3.innerHTML = score.value
  103. td4.innerHTML = '<a href="javascript:;">删除</a>'
  104. tr.appendChild(td1)
  105. tr.appendChild(td2)
  106. tr.appendChild(td3)
  107. tr.appendChild(td4)
  108. tbody.appendChild(tr)
  109. name.value = ''
  110. sub.value = ''
  111. score.value = ''
  112. }
  113. let three1 = document.querySelectorAll('tbody tr td:nth-child(3)')
  114. let sum = 0
  115. for (let j = 0; j < three1.length; j++) {
  116. sum += (three1[j].innerHTML - 0)
  117. }
  118. //总分
  119. total.innerHTML = `${sum}`
  120. //平均值
  121. avg.innerHTML = `${sum / three1.length}`
  122. //给创建的a添加删除的点击事件
  123. let as = document.querySelectorAll('a')
  124. for (let i = 0; i < as.length; i++) {
  125. as[i].addEventListener('click', function () {
  126. // tbody.removeChild(this.parentNode.parentNode)
  127. sum -= (three1[i].innerHTML - 0)
  128. this.parentNode.parentNode.remove()
  129. total.innerHTML = `${sum}`
  130. // total.innerHTML = `${sum - (three1[i].innerHTML - 0)}`
  131. let three = document.querySelectorAll('tbody tr td:nth-child(3)')
  132. avg.innerHTML = `${(sum / three.length).toFixed(2) === 'NaN' ? 0 : (sum / three.length).toFixed(2)}`
  133. })
  134. }
  135. })
  136. </script>
  137. </body>
  138. </html>

2、通过渲染表格,事件委托实现

思路:先把整体的效果图写出来,再通过js渲染到页面上,每次添加一组数据就相当于给数组添加数据,删除事件用事件委托,给祖先元素绑定事件,子元素触发事件会冒泡到祖先元素。

css代码

  1. .score-case {
  2. width: 1000px;
  3. margin: 50px auto;
  4. display: flex;
  5. }
  6. .score-case .table {
  7. flex: 4;
  8. }
  9. .score-case .table table {
  10. width: 100%;
  11. border-spacing: 0;
  12. border-top: 1px solid #ccc;
  13. border-left: 1px solid #ccc;
  14. }
  15. .score-case .table table th {
  16. background: #f5f5f5;
  17. }
  18. .score-case .table table tr:hover td {
  19. background: #f5f5f5;
  20. }
  21. .score-case .table table td,
  22. .score-case .table table th {
  23. border-bottom: 1px solid #ccc;
  24. border-right: 1px solid #ccc;
  25. text-align: center;
  26. padding: 10px;
  27. }
  28. .score-case .table table td.red,
  29. .score-case .table table th.red {
  30. color: red;
  31. }
  32. .score-case .table .none {
  33. height: 100px;
  34. line-height: 100px;
  35. color: #999;
  36. }
  37. .score-case .form {
  38. flex: 1;
  39. padding: 20px;
  40. }
  41. .score-case .form .form-item {
  42. display: flex;
  43. margin-bottom: 20px;
  44. align-items: center;
  45. }
  46. .score-case .form .form-item .label {
  47. width: 60px;
  48. text-align: right;
  49. font-size: 14px;
  50. }
  51. .score-case .form .form-item .input {
  52. flex: 1;
  53. }
  54. .score-case .form .form-item input,
  55. .score-case .form .form-item select {
  56. appearance: none;
  57. outline: none;
  58. border: 1px solid #ccc;
  59. width: 200px;
  60. height: 40px;
  61. box-sizing: border-box;
  62. padding: 10px;
  63. color: #666;
  64. }
  65. .score-case .form .form-item input::placeholder {
  66. color: #666;
  67. }
  68. .score-case .form .form-item .cancel,
  69. .score-case .form .form-item .submit {
  70. appearance: none;
  71. outline: none;
  72. border: 1px solid #ccc;
  73. border-radius: 4px;
  74. padding: 4px 10px;
  75. margin-right: 10px;
  76. font-size: 12px;
  77. background: #ccc;
  78. }
  79. .score-case .form .form-item .submit {
  80. border-color: #069;
  81. background: #069;
  82. color: #fff;
  83. }

html代码

  1. <div id="app" class="score-case">
  2. <div class="table">
  3. <table>
  4. <thead>
  5. <tr>
  6. <th>姓名</th>
  7. <th>科目</th>
  8. <th>成绩</th>
  9. <th>操作</th>
  10. </tr>
  11. </thead>
  12. <tbody>
  13. <!-- <tr>
  14. <td>1</td>
  15. <td>语文</td>
  16. <td class="red">46</td>
  17. <td><a href="#">删除</a></td>
  18. </tr> -->
  19. </tbody>
  20. <tfoot>
  21. <tr>
  22. <td colspan="5">
  23. <span class="total">总分:246</span>
  24. <span style="margin-left: 50px" class="average"
  25. >平均分:79</span
  26. >
  27. </td>
  28. </tr>
  29. </tfoot>
  30. </table>
  31. </div>
  32. <div class="form">
  33. <div class="form-item">
  34. <div class="label">姓名:</div>
  35. <div class="input">
  36. <input type="text" placeholder="请输入姓名" class="username" />
  37. </div>
  38. </div>
  39. <div class="form-item">
  40. <div class="label">科目:</div>
  41. <div class="input">
  42. <input type="text" placeholder="请输入科目" class="subject" />
  43. </div>
  44. </div>
  45. <div class="form-item">
  46. <div class="label">分数:</div>
  47. <div class="input">
  48. <input type="text" placeholder="请输入分数" class="score" />
  49. </div>
  50. </div>
  51. <div class="form-item">
  52. <div class="label"></div>
  53. <div class="input">
  54. <button class="submit">添加</button>
  55. </div>
  56. </div>
  57. </div>
  58. </div>

js代码

  1. <script>
  2. const list = [
  3. {
  4. uname: '张三',
  5. subject: '语文',
  6. score: 20,
  7. },
  8. {
  9. uname: '李四',
  10. subject: '数学',
  11. score: 20,
  12. },
  13. {
  14. uname: '王五',
  15. subject: '英文',
  16. score: 20,
  17. },
  18. ]
  19. // 1 基于数据渲染页面
  20. function render() {
  21. let str = ''
  22. let sum = 0
  23. for (let i = 0; i < list.length; i++) {
  24. sum += list[i].score
  25. str += `
  26. <tr>
  27. <td>${list[i].uname}</td>
  28. <td>${list[i].subject}</td>
  29. <td class="red">${list[i].score}</td>
  30. <td><a href="#" data-id=${i}>删除</a></td>
  31. </tr>
  32. `
  33. }
  34. document.querySelector('.score-case tbody').innerHTML = str
  35. // 计算总分 平均分 渲染到页面
  36. document.querySelector('.total').innerHTML = `总分:${sum}`
  37. document.querySelector('.average').innerHTML = `平均分:${
  38. (sum / list.length).toFixed(2) === 'NaN'
  39. ? 0
  40. : (sum / list.length).toFixed(2)
  41. }`
  42. }
  43. render()
  44. // 2 添加业务
  45. const submit = document.querySelector('.submit')
  46. submit.addEventListener('click', function () {
  47. const uname = document.querySelector('.username')
  48. const subject = document.querySelector('.subject')
  49. const score = document.querySelector('.score')
  50. const uname_v = uname.value.trim()
  51. const subject_v = subject.value.trim()
  52. const score_v = +score.value.trim()
  53. if (!uname_v || !subject_v || !score_v) {
  54. alert('姓名、科目 或分数都不能为空 ')
  55. return
  56. }
  57. list.push({
  58. uname: uname_v,
  59. subject: subject_v,
  60. score: score_v,
  61. })
  62. // 重新渲染
  63. render()
  64. // 清空文本框
  65. uname.value = ''
  66. subject.value = ''
  67. score.value = ''
  68. })
  69. // 3 删除
  70. document.querySelector('tbody').addEventListener('click', function (e) {
  71. console.log(e.target.dataset.id)
  72. // 把数组中对应的数据删除
  73. list.splice(e.target.dataset.id, 1)
  74. // 重新渲染
  75. render()
  76. })
  77. </script>

完整代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <link rel="stylesheet" href="./styles/index.css" />
  8. <title>Document</title>
  9. </head>
  10. <body>
  11. <div id="app" class="score-case">
  12. <div class="table">
  13. <table>
  14. <thead>
  15. <tr>
  16. <th>姓名</th>
  17. <th>科目</th>
  18. <th>成绩</th>
  19. <th>操作</th>
  20. </tr>
  21. </thead>
  22. <tbody>
  23. <!-- <tr>
  24. <td>1</td>
  25. <td>语文</td>
  26. <td class="red">46</td>
  27. <td><a href="#">删除</a></td>
  28. </tr> -->
  29. </tbody>
  30. <tfoot>
  31. <tr>
  32. <td colspan="5">
  33. <span class="total">总分:246</span>
  34. <span style="margin-left: 50px" class="average"
  35. >平均分:79</span
  36. >
  37. </td>
  38. </tr>
  39. </tfoot>
  40. </table>
  41. </div>
  42. <div class="form">
  43. <div class="form-item">
  44. <div class="label">姓名:</div>
  45. <div class="input">
  46. <input type="text" placeholder="请输入姓名" class="username" />
  47. </div>
  48. </div>
  49. <div class="form-item">
  50. <div class="label">科目:</div>
  51. <div class="input">
  52. <input type="text" placeholder="请输入科目" class="subject" />
  53. </div>
  54. </div>
  55. <div class="form-item">
  56. <div class="label">分数:</div>
  57. <div class="input">
  58. <input type="text" placeholder="请输入分数" class="score" />
  59. </div>
  60. </div>
  61. <div class="form-item">
  62. <div class="label"></div>
  63. <div class="input">
  64. <button class="submit">添加</button>
  65. </div>
  66. </div>
  67. </div>
  68. </div>
  69. <script>
  70. const list = [
  71. {
  72. uname: '张三',
  73. subject: '语文',
  74. score: 20,
  75. },
  76. {
  77. uname: '李四',
  78. subject: '数学',
  79. score: 20,
  80. },
  81. {
  82. uname: '王五',
  83. subject: '英文',
  84. score: 20,
  85. },
  86. ]
  87. // 1 基于数据渲染页面
  88. function render() {
  89. let str = ''
  90. let sum = 0
  91. for (let i = 0; i < list.length; i++) {
  92. sum += list[i].score
  93. str += `
  94. <tr>
  95. <td>${list[i].uname}</td>
  96. <td>${list[i].subject}</td>
  97. <td class="red">${list[i].score}</td>
  98. <td><a href="#" data-id=${i}>删除</a></td>
  99. </tr>
  100. `
  101. }
  102. document.querySelector('.score-case tbody').innerHTML = str
  103. // 计算总分 平均分 渲染到页面
  104. document.querySelector('.total').innerHTML = `总分:${sum}`
  105. document.querySelector('.average').innerHTML = `平均分:${
  106. (sum / list.length).toFixed(2) === 'NaN'
  107. ? 0
  108. : (sum / list.length).toFixed(2)
  109. }`
  110. }
  111. render()
  112. // 2 添加业务
  113. const submit = document.querySelector('.submit')
  114. submit.addEventListener('click', function () {
  115. const uname = document.querySelector('.username')
  116. const subject = document.querySelector('.subject')
  117. const score = document.querySelector('.score')
  118. const uname_v = uname.value.trim()
  119. const subject_v = subject.value.trim()
  120. const score_v = +score.value.trim()
  121. if (!uname_v || !subject_v || !score_v) {
  122. alert('姓名、科目 或分数都不能为空 ')
  123. return
  124. }
  125. list.push({
  126. uname: uname_v,
  127. subject: subject_v,
  128. score: score_v,
  129. })
  130. // 重新渲染
  131. render()
  132. // 清空文本框
  133. uname.value = ''
  134. subject.value = ''
  135. score.value = ''
  136. })
  137. // 3 删除
  138. document.querySelector('tbody').addEventListener('click', function (e) {
  139. console.log(e.target.dataset.id)
  140. // 把数组中对应的数据删除
  141. list.splice(e.target.dataset.id, 1)
  142. // 重新渲染
  143. render()
  144. })
  145. </script>
  146. </body>
  147. </html>

效果图

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/888730
推荐阅读
相关标签
  

闽ICP备14008679号