目录
1、通过创建节点实现
css代码
html代码
js代码
完整代码
2、通过渲染表格,事件委托实现
css代码
html代码
js代码
完整代码
效果图
1、通过创建节点实现
思路:先把整体的html结构写出来,table表格分为3部分,其中tbody中的内容通过节点创建出来,删除时,找到其祖先元素的节点进行remove(),表单内的各个框的值对应表格的内容。
css代码
<style>.wrapper {display: flex;margin-left: 100px;margin-top: 100px;}.box {width: 300px;height: 400px;/* border: 2px solid red; */margin-left: 50px;}input {height: 40px;width: 200px;margin-bottom: 30px;}button {background-color: #23669a;color: white;width: 50px;height: 30px;border-radius: 5px;outline: none;border: none;margin-left: 50px;}table {border: 1px solid #dbdbdb;border-collapse: collapse;}table tr,th,td {height: 50px;width: 180px;border: 1px solid #dbdbdb;text-align: center;}thead tr {background-color: #f4f4f5;}tbody tr td:nth-child(3) {color: #f54d7b;}</style>
html代码
<div class="wrapper"><div><table><thead><th>姓名</th><th>科目</th><th>成绩</th><th>操作</th></thead><tbody></tbody><tfoot><tr><td colspan="4"> 总分:<span class="total"></span>平均分: <span class="avg"></span></td></tr></tfoot></table></div><div class="box">姓名:<input type="text" placeholder="请输入姓名" class="name"><br>科目:<input type="text" placeholder="请输入科目" class="sub"><br>分数:<input type="text" placeholder="请输入分数" class="score"><br><button>添加</button></div></div>
js代码
<script>//获取元素const tbody = document.querySelector('tbody')const btn = document.querySelector('button')const name = document.querySelector('.name')const sub = document.querySelector('.sub')const score = document.querySelector('.score')let total = document.querySelector('.total')let avg = document.querySelector('.avg')//给按钮添加点击事件btn.addEventListener('click', function () {//创建元素const tr = document.createElement('tr')const td1 = document.createElement('td')const td2 = document.createElement('td')const td3 = document.createElement('td')const td4 = document.createElement('td')if(name.value===''||sub.value===''||score.value===''){alert('姓名,科目,成绩不能为空')}else{td1.innerHTML = name.valuetd2.innerHTML = sub.valuetd3.innerHTML = score.valuetd4.innerHTML = '<a href="javascript:;">删除</a>'tr.appendChild(td1)tr.appendChild(td2)tr.appendChild(td3)tr.appendChild(td4)tbody.appendChild(tr)name.value = ''sub.value = ''score.value = ''}let three1 = document.querySelectorAll('tbody tr td:nth-child(3)')let sum = 0for (let j = 0; j < three1.length; j++) {sum += (three1[j].innerHTML - 0)}//总分total.innerHTML = `${sum}`//平均值avg.innerHTML = `${sum / three1.length}`//给创建的a添加删除的点击事件let as = document.querySelectorAll('a')for (let i = 0; i < as.length; i++) {as[i].addEventListener('click', function () {// tbody.removeChild(this.parentNode.parentNode)sum -= (three1[i].innerHTML - 0)this.parentNode.parentNode.remove()total.innerHTML = `${sum}`// total.innerHTML = `${sum - (three1[i].innerHTML - 0)}`let three = document.querySelectorAll('tbody tr td:nth-child(3)')avg.innerHTML = `${(sum / three.length).toFixed(2) === 'NaN' ? 0 : (sum / three.length).toFixed(2)}`})}})</script>
完整代码
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>.wrapper {display: flex;margin-left: 100px;margin-top: 100px;}.box {width: 300px;height: 400px;/* border: 2px solid red; */margin-left: 50px;}input {height: 40px;width: 200px;margin-bottom: 30px;}button {background-color: #23669a;color: white;width: 50px;height: 30px;border-radius: 5px;outline: none;border: none;margin-left: 50px;}table {border: 1px solid #dbdbdb;border-collapse: collapse;}table tr,th,td {height: 50px;width: 180px;border: 1px solid #dbdbdb;text-align: center;}thead tr {background-color: #f4f4f5;}tbody tr td:nth-child(3) {color: #f54d7b;}</style>
</head><body><div class="wrapper"><div><table><thead><th>姓名</th><th>科目</th><th>成绩</th><th>操作</th></thead><tbody></tbody><tfoot><tr><td colspan="4"> 总分:<span class="total"></span>平均分: <span class="avg"></span></td></tr></tfoot></table></div><div class="box">姓名:<input type="text" placeholder="请输入姓名" class="name"><br>科目:<input type="text" placeholder="请输入科目" class="sub"><br>分数:<input type="text" placeholder="请输入分数" class="score"><br><button>添加</button></div></div><script>//获取元素const tbody = document.querySelector('tbody')const btn = document.querySelector('button')const name = document.querySelector('.name')const sub = document.querySelector('.sub')const score = document.querySelector('.score')let total = document.querySelector('.total')let avg = document.querySelector('.avg')//给按钮添加点击事件btn.addEventListener('click', function () {//创建元素const tr = document.createElement('tr')const td1 = document.createElement('td')const td2 = document.createElement('td')const td3 = document.createElement('td')const td4 = document.createElement('td')if(name.value===''||sub.value===''||score.value===''){alert('姓名,科目,成绩不能为空')}else{td1.innerHTML = name.valuetd2.innerHTML = sub.valuetd3.innerHTML = score.valuetd4.innerHTML = '<a href="javascript:;">删除</a>'tr.appendChild(td1)tr.appendChild(td2)tr.appendChild(td3)tr.appendChild(td4)tbody.appendChild(tr)name.value = ''sub.value = ''score.value = ''}let three1 = document.querySelectorAll('tbody tr td:nth-child(3)')let sum = 0for (let j = 0; j < three1.length; j++) {sum += (three1[j].innerHTML - 0)}//总分total.innerHTML = `${sum}`//平均值avg.innerHTML = `${sum / three1.length}`//给创建的a添加删除的点击事件let as = document.querySelectorAll('a')for (let i = 0; i < as.length; i++) {as[i].addEventListener('click', function () {// tbody.removeChild(this.parentNode.parentNode)sum -= (three1[i].innerHTML - 0)this.parentNode.parentNode.remove()total.innerHTML = `${sum}`// total.innerHTML = `${sum - (three1[i].innerHTML - 0)}`let three = document.querySelectorAll('tbody tr td:nth-child(3)')avg.innerHTML = `${(sum / three.length).toFixed(2) === 'NaN' ? 0 : (sum / three.length).toFixed(2)}`})}})</script></body></html>
2、通过渲染表格,事件委托实现
思路:先把整体的效果图写出来,再通过js渲染到页面上,每次添加一组数据就相当于给数组添加数据,删除事件用事件委托,给祖先元素绑定事件,子元素触发事件会冒泡到祖先元素。
css代码
.score-case {width: 1000px;margin: 50px auto;display: flex;
}
.score-case .table {flex: 4;
}
.score-case .table table {width: 100%;border-spacing: 0;border-top: 1px solid #ccc;border-left: 1px solid #ccc;
}
.score-case .table table th {background: #f5f5f5;
}
.score-case .table table tr:hover td {background: #f5f5f5;
}
.score-case .table table td,
.score-case .table table th {border-bottom: 1px solid #ccc;border-right: 1px solid #ccc;text-align: center;padding: 10px;
}
.score-case .table table td.red,
.score-case .table table th.red {color: red;
}
.score-case .table .none {height: 100px;line-height: 100px;color: #999;
}
.score-case .form {flex: 1;padding: 20px;
}
.score-case .form .form-item {display: flex;margin-bottom: 20px;align-items: center;
}
.score-case .form .form-item .label {width: 60px;text-align: right;font-size: 14px;
}
.score-case .form .form-item .input {flex: 1;
}
.score-case .form .form-item input,
.score-case .form .form-item select {appearance: none;outline: none;border: 1px solid #ccc;width: 200px;height: 40px;box-sizing: border-box;padding: 10px;color: #666;
}
.score-case .form .form-item input::placeholder {color: #666;
}
.score-case .form .form-item .cancel,
.score-case .form .form-item .submit {appearance: none;outline: none;border: 1px solid #ccc;border-radius: 4px;padding: 4px 10px;margin-right: 10px;font-size: 12px;background: #ccc;
}
.score-case .form .form-item .submit {border-color: #069;background: #069;color: #fff;
}
html代码
<div id="app" class="score-case"><div class="table"><table><thead><tr><th>姓名</th><th>科目</th><th>成绩</th><th>操作</th></tr></thead><tbody><!-- <tr><td>1</td><td>语文</td><td class="red">46</td><td><a href="#">删除</a></td></tr> --></tbody><tfoot><tr><td colspan="5"><span class="total">总分:246</span><span style="margin-left: 50px" class="average">平均分:79</span></td></tr></tfoot></table></div><div class="form"><div class="form-item"><div class="label">姓名:</div><div class="input"><input type="text" placeholder="请输入姓名" class="username" /></div></div><div class="form-item"><div class="label">科目:</div><div class="input"><input type="text" placeholder="请输入科目" class="subject" /></div></div><div class="form-item"><div class="label">分数:</div><div class="input"><input type="text" placeholder="请输入分数" class="score" /></div></div><div class="form-item"><div class="label"></div><div class="input"><button class="submit">添加</button></div></div></div></div>
js代码
<script>const list = [{uname: '张三',subject: '语文',score: 20,},{uname: '李四',subject: '数学',score: 20,},{uname: '王五',subject: '英文',score: 20,},]// 1 基于数据渲染页面function render() {let str = ''let sum = 0for (let i = 0; i < list.length; i++) {sum += list[i].scorestr += `<tr><td>${list[i].uname}</td><td>${list[i].subject}</td><td class="red">${list[i].score}</td><td><a href="#" data-id=${i}>删除</a></td></tr>`}document.querySelector('.score-case tbody').innerHTML = str// 计算总分 平均分 渲染到页面document.querySelector('.total').innerHTML = `总分:${sum}`document.querySelector('.average').innerHTML = `平均分:${(sum / list.length).toFixed(2) === 'NaN'? 0: (sum / list.length).toFixed(2)}`}render()// 2 添加业务const submit = document.querySelector('.submit')submit.addEventListener('click', function () {const uname = document.querySelector('.username')const subject = document.querySelector('.subject')const score = document.querySelector('.score')const uname_v = uname.value.trim()const subject_v = subject.value.trim()const score_v = +score.value.trim()if (!uname_v || !subject_v || !score_v) {alert('姓名、科目 或分数都不能为空 ')return}list.push({uname: uname_v,subject: subject_v,score: score_v,})// 重新渲染render()// 清空文本框uname.value = ''subject.value = ''score.value = ''})// 3 删除document.querySelector('tbody').addEventListener('click', function (e) {console.log(e.target.dataset.id)// 把数组中对应的数据删除list.splice(e.target.dataset.id, 1)// 重新渲染render()})</script>
完整代码
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><link rel="stylesheet" href="./styles/index.css" /><title>Document</title></head><body><div id="app" class="score-case"><div class="table"><table><thead><tr><th>姓名</th><th>科目</th><th>成绩</th><th>操作</th></tr></thead><tbody><!-- <tr><td>1</td><td>语文</td><td class="red">46</td><td><a href="#">删除</a></td></tr> --></tbody><tfoot><tr><td colspan="5"><span class="total">总分:246</span><span style="margin-left: 50px" class="average">平均分:79</span></td></tr></tfoot></table></div><div class="form"><div class="form-item"><div class="label">姓名:</div><div class="input"><input type="text" placeholder="请输入姓名" class="username" /></div></div><div class="form-item"><div class="label">科目:</div><div class="input"><input type="text" placeholder="请输入科目" class="subject" /></div></div><div class="form-item"><div class="label">分数:</div><div class="input"><input type="text" placeholder="请输入分数" class="score" /></div></div><div class="form-item"><div class="label"></div><div class="input"><button class="submit">添加</button></div></div></div></div><script>const list = [{uname: '张三',subject: '语文',score: 20,},{uname: '李四',subject: '数学',score: 20,},{uname: '王五',subject: '英文',score: 20,},]// 1 基于数据渲染页面function render() {let str = ''let sum = 0for (let i = 0; i < list.length; i++) {sum += list[i].scorestr += `<tr><td>${list[i].uname}</td><td>${list[i].subject}</td><td class="red">${list[i].score}</td><td><a href="#" data-id=${i}>删除</a></td></tr>`}document.querySelector('.score-case tbody').innerHTML = str// 计算总分 平均分 渲染到页面document.querySelector('.total').innerHTML = `总分:${sum}`document.querySelector('.average').innerHTML = `平均分:${(sum / list.length).toFixed(2) === 'NaN'? 0: (sum / list.length).toFixed(2)}`}render()// 2 添加业务const submit = document.querySelector('.submit')submit.addEventListener('click', function () {const uname = document.querySelector('.username')const subject = document.querySelector('.subject')const score = document.querySelector('.score')const uname_v = uname.value.trim()const subject_v = subject.value.trim()const score_v = +score.value.trim()if (!uname_v || !subject_v || !score_v) {alert('姓名、科目 或分数都不能为空 ')return}list.push({uname: uname_v,subject: subject_v,score: score_v,})// 重新渲染render()// 清空文本框uname.value = ''subject.value = ''score.value = ''})// 3 删除document.querySelector('tbody').addEventListener('click', function (e) {console.log(e.target.dataset.id)// 把数组中对应的数据删除list.splice(e.target.dataset.id, 1)// 重新渲染render()})</script></body>
</html>