1.html
<table border="1" cellpadding="10" cellspacing="0"> <thead> <th>商品</th> <th>价格</th> <th>数量</th> <th>操作</th> </thead> <tbody id="content"> </tbody> <tfoot id="sta"> </tfoot> </table> <button style="margin: 10px;" onclick="show()">添加商品</button> <div style="display: none;" id="put"> <input type="text" placeholder="商品名称" id="name" value=""> <input type="text" placeholder="商品价格" id="price" value=""> <input type="text" placeholder="商品数量" id="num" value=""> <button onclick="addition()">确认</button> <button onclick="conceal()">取消</button> </div>
2、Script
let con = document.getElementById('content'); let put = document.getElementById('put'); let name = document.getElementById('name'); let price = document.getElementById('price'); let num = document.getElementById('num'); let sta = document.getElementById('sta'); let total_price = 0; let total_num = 0; let conte = [{ "name": "商品一", "price": 120, "num": 0 }, { "name": "商品二", "price": 99, "num": 0 }, { "name": "商品三", "price": 150, "num": 0 } ] let len = conte.length; apply(conte); //根据内容渲染表格函数 function apply(arr) { let str = ''; for (let i = 0; i < arr.length; i++) { str += ` <tr> <td>${arr[i].name}</td> <td>${arr[i].price}</td> <td> <button onclick="sub(${i})" style="display: ${arr[i].num == 0 ? 'none' : 'inline-block'};">-</button> ${arr[i].num} <button onclick="add(${i})">+</button> </td> <td> <button onclick="redact(${i})">编辑</button> <button onclick="dele(${i})">删除</button> </td> </tr> `; } con.innerHTML = str; } //加号按钮 function add(a) { conte[a].num += 1; agg(conte); static(); apply(conte); } //减号按钮 function sub(a) { conte[a].num -= 1; agg(conte); static(); apply(conte); } //金额总计 agg(conte); function agg(arr) { for (let i = 0; i < arr.length; i++) { total_price += parseFloat(arr[i].price) * parseFloat(arr[i].num); total_num += parseFloat(arr[i].num); } } //表格底部统计 static(); function static() { let str = ''; str = ` <tr> <td>总计</td> <td>金额:${total_price}</td> <td>数量:${total_num}</td> <td></td> </tr> `; total_num = 0; total_price = 0; sta.innerHTML = str; } //显示输入框 function show() { name.value = ''; price.value = ''; num.value = ''; put.style.display = 'block'; } //隐藏输入框 function conceal() { name.value = ''; price.value = ''; num.value = ''; put.style.display = 'none'; } //删除事件 function dele(a) { conte.splice(a, 1); agg(conte); static(); apply(conte); } //编辑事件 function redact(a) { show(); name.value = conte[a].name; price.value = conte[a].price; num.value = conte[a].num; len = a; } //添加编辑事件 function addition() { let str = { "name": "", "price": null, "num": null } if (len < conte.length) { conte[len].name = name.value; conte[len].price = parseFloat(price.value); conte[len].num = parseFloat(num.value); len = conte.length; conceal(); agg(conte); static(); apply(conte); } else { str.name = name.value; str.price = parseFloat(price.value); str.num = parseFloat(num.value); conte.push(str); conceal(); agg(conte); static(); apply(conte); } }
3、结果: