html:
<table border="1" cellspacing="0" cellpadding="20"> <thead> <tr> <th>名称</th> <th>价格</th> <th>数量</th> <th>操作</th> </tr> </thead> <tbody id="tbody"></tbody> <tfoot> <tr> <th></th> <th id="priceAll">总价:¥0</th> <th id="numAll">总数:0</th> <th></th> </tr> </tfoot> </table> <button onclick="isShow()">添加商品</button> <div style="display: none;" id="tool"> <input type="text" id="name" placeholder="请输入商品名称"> <input type="text" id="price" placeholder="请输入商品价格"> <input type="text" id="num" placeholder="请输入商品数量"> <button onclick="isConfig()">确定</button> <button onclick="isClose()">取消</button> </div>
js:
<script> // 初始数据 let data = [{ name: "商品一", price: 33.00, num: 3 }, { name: "商品二", price: 66.00, num: 0 }, { name: "商品三", price: 99.00, num: 0 }, ] let priceAll = 0; let numAll = 0; let index = -1; // 执行渲染 renders() // 创建渲染函数 function renders() { let str = ""; for (let i = 0; i < data.length; i++) { str += ` <tr> <td>${data[i].name}</td> <td>¥${data[i].price}</td> <td> <button onclick="sub(${i})" style="display:${data[i].num == 0 ? 'none' : 'inline-block'};">-</button> <span>${data[i].num}</span> <button onclick="add(${i})">+</button> </td> <td> <button onclick="edit(${i})">编辑</button> <button onclick="del(${i})">删除</button> </td> </tr> `; } document.getElementById("tbody").innerHTML = str; counts(); } // 数量添加功能 function add(i) { data[i].num++; renders(); } // 数量减少功能 function sub(i){ data[i].num--; renders(); } // 计算总价数量 function counts(){ priceAll = 0; numAll = 0; for (let i = 0; i < data.length; i++) { priceAll += parseFloat(data[i].num) * parseFloat(data[i].price); numAll += parseFloat(data[i].num); } document.getElementById("priceAll").innerHTML = '总价:¥' + priceAll; document.getElementById("numAll").innerHTML = '总数:' + numAll; } // 商品删除功能 function del(i){ // 数组.splice(从哪删,删几个,添加的值) data.splice(i,1); renders(); } // 添加商品显示 function isShow(){ index = -1; document.getElementById("tool").style.display = "block"; } // 确定添加/编辑 function isConfig(){ let name = document.getElementById("name").value; let price = document.getElementById("price").value; let num = document.getElementById("num").value; if( name != '' && price != "" && num !=""){ if(index > -1){ data.splice(index,1,{ name, price, num }); }else{ data.push({ name, price, num }); } isClose(); renders(); }else{ alert("请完善商品信息") } } // 取消事件 function isClose(){ index = -1; document.getElementById("name").value = ""; document.getElementById("price").value = ""; document.getElementById("num").value = ""; document.getElementById("tool").style.display = "none"; } // 编辑回显 function edit(i){ index = i; document.getElementById("tool").style.display = "block"; document.getElementById("name").value = data[i].name; document.getElementById("price").value = data[i].price; document.getElementById("num").value = data[i].num ; console.log(data[i]); } </script>