<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
/*table样式*/
.content table {
border-collapse: collapse;
width: 600px;
}
.content table th, td {
min-width: 100px;
border: 1px solid grey;
text-align: center;
}
/*加减号的样式*/
.wrap {
width: 80px;
height: 27px;
margin: 0 auto;
}
.wrap span {
display: inline-block;
border: 1px solid #a0a0a0;
width: 25px;
height: 25px;
float: left;
text-align: center;
line-height: 25px;
cursor: pointer;
}
.wrap .show-num {
cursor: default;
width: 25px;
height: 25px;
float: left;
border-style: none;
padding: 0;
text-align: center;
border-top: 1px solid gray;
border-bottom: 1px solid gray;
}
.prices {
margin-top: 10px;
}
.btns {
margin-bottom: 10px;
}
/*背景颜色的类*/
.bgc {
background-color: #f1f1f1;
}
</style>
</head>
<body>
<pre>
<s>0. 搞清楚代码</s>
<s>1. 选中变色</s>
<s>2. 逐个勾选到时候,勾选所有</s>
<s>3. 排序</s>
<s>4. (搜索)</s>
<s>5. 对数字直接进行修改</s>
<s>6. (计算选中商品价格)</s>
<s>7. 修改为事件委托</s>
1.添加
2.删除
3.修改
4.修改库存
5.勾选
6.排序
(7.操作数组)
</pre>
<div class="btns">
商品名称:<input type="text" id="ipt-name">
商品价格:<input type="text" id="ipt-price">
<br>
<br>
<button id="btn-add">添加商品</button>
<button id="btn-delete">删除选中</button>
<button id="btn-sort">价格排序</button>
<button id="btn-compute">勾选总价</button>
</div>
<div class="content">
<table>
<thead>
<tr>
<th>商品名称</th>
<th>商品价格</th>
<th>全选 <input type="checkbox" id="check-all"></th>
<th>修改库存</th>
<th>修改单价</th>
<th>删除商品</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="prices">
商品总价:<span id="total-money">0</span>
商品均价:<span id="avg-money">0</span>
</div>
</body>
<script>
var rawStr = "可乐-3,雪碧-2.5,矿泉水-2,辣条-4";
var objArr = [];
buildItemsArray();
printTableInfo();
bindEvents();
//绑定所有的DOM事件
function bindEvents() {
checkAllEvent();
addItemEvent();
deleteItemEvent();
sortItemEvent();
computeSelectedEvent();
}
//checkbox全选的事件
function checkAllEvent() {
var checkAll = document.querySelector("#check-all");
checkAll.onclick = function () {
//获取表格中除表头外所有的tr中的checkbox
var checks = document.querySelectorAll(".item-check");
for (var i = 0; i < checks.length; i++) {
//为获取的每一个checkbox指定当前checkall的选中状态
checks[i].checked = this.checked;
var tr = checks[i].parentElement.parentElement;
//根据当前的checkall状态改变下列tr的背景颜色
if (this.checked) {
tr.style.backgroundColor = "#f1f1f1";
} else {
tr.style.backgroundColor = "white";
}
}
};
}
//add添加商品事件
function addItemEvent() {
var btnAdd = document.querySelector("#btn-add");
btnAdd.onclick = function () {
//获取输入的input
var iptName = document.querySelector("#ipt-name");
var iptPrice = document.querySelector("#ipt-price");
//获取输入的值,判断不为空
var nameVal = iptName.value;
var priceVal = iptPrice.value;
if (nameVal === "" || priceVal === "") {
alert("缺失信息");
return;
}
var newItem = {
name: nameVal,
price: priceVal
};
var table = document.querySelector("table");
var tbody = document.querySelector("tbody");
var tr = addOneRow(newItem);
tbody.appendChild(tr);
iptName.value = "";
iptPrice.value = "";
};
}
//delete删除商品事件
function deleteItemEvent() {
var btnDelete = document.querySelector("#btn-delete");
btnDelete.onclick = function () {
var checks = document.querySelectorAll(".item-check");
for (var i = 0; i < checks.length; i++) {
if (checks[i].checked) {
checks[i].parentElement.parentElement.remove();
}
}
//重新计算当前剩余商品的价格
computeMoney();
};
}
//sort对商品价格排序
function sortItemEvent() {
var btnSort = document.querySelector("#btn-sort");
btnSort.onclick = function () {
var trs = document.querySelectorAll(".item-tr");
// var trsArray = [];
// for (var i = 0; i < trs.length; i++) {
// trsArray.push(trs[i]);
// }
//将一个可迭代的类数组转换为数组形式
var trsArray = Array.from(trs);
//按照tr中的价格进行排序
trsArray.sort(function (tr1, tr2) {
// return Number(tr1.children[1].innerHTML) - Number(tr2.children[1].innerHTML);
return tr1.children[1].innerHTML - tr2.children[1].innerHTML;
});
//将排序后的tr重新输出到tbody中
var table = document.querySelector("table");
var tbody = table.querySelector("tbody");
tbody.innerHTML = "";
for (var i = 0; i < trsArray.length; i++) {
tbody.appendChild(trsArray[i]);
}
};
}
//计算勾选事件
function computeSelectedEvent() {
var btnCompute = document.querySelector("#btn-compute");
btnCompute.addEventListener("click", function () {
computeSelectedMoney();
})
}
//一. 切分字符串,创建对象数组
function buildItemsArray() {
//第一次切分
var preStr = rawStr.split(",");
for (var i = 0; i < preStr.length; i++) {
//第二次切分
var arr = preStr[i].split("-"); //名称,价格
var obj = {
name: arr[0],
price: arr[1]
};
//将创建好单个商品的对象存入数组当中
objArr.push(obj);
}
console.log(objArr);
}
//增加数字
function addNum(self) {
//获取到展示数字的对象 next
var show = self.nextElementSibling;
var oldNum = show.value - 0;
var newNum = oldNum + 1;
show.value = newNum;
computeMoney();
}
//减少数字
function subNum(self) {
//获取到展示数字的对象 previous
var show = self.previousElementSibling;
var oldNum = show.value - 0;
var newNum = oldNum - 1;
//判断数字的界限
if (newNum <= 0) {
newNum = 0
}
show.value = newNum;
computeMoney();
}
//直接修改数字
function changeNum(self) {
//对不合法的输入做替换
self.value = self.value.replace(/[^\d]/g, "");
if (self.value === "") {
self.value = "0";
}
//重新计算价格
computeMoney();
}
//添加一行tr的操作
//obj为要在当前行添加的商品对象
function addOneRow(obj) {
var tr = document.createElement("tr");
tr.classList.add("item-tr");
var td1 = document.createElement("td");
td1.innerHTML = obj.name;
var td2 = document.createElement("td");
//为商品单价的单元格添加类名
td2.classList.add("item-money");
td2.innerHTML = obj.price;
var td3 = document.createElement("td");
var check = document.createElement("input");
check.type = "checkbox";
//为每一行的checkbox添加类名,为了方便选取操作
check.classList.add("item-check");
//选中当前行变色
check.onclick = function () {
//1.通过类名
//当此类名不存在,则添加
//当此类名存在,则移除
// this.parentElement.parentElement.classList.toggle("bgc");
//2.通过对状态判断
var currTr = this.parentElement.parentElement;
if (this.checked) {
currTr.style.backgroundColor = "#f1f1f1";
} else {
currTr.style.backgroundColor = "#fff";
}
var checks = document.querySelectorAll(".item-check");
var checkAll = document.querySelector("#check-all");
//反选 统计被勾选的checkbox数量
var count = 0;
for (var i = 0; i < checks.length; i++) {
if (checks[i].checked) {
count += 1;
}
}
//被勾选的checkbox数量与其数组长度相等
if (count === checks.length) {
checkAll.checked = true;
} else {
checkAll.checked = false;
}
};
td3.appendChild(check);
var td4 = document.createElement("td");
td4.innerHTML = `<div class="wrap">
<span class="add-num" onclick="addNum(this)">+</span>
<input type="text" class="show-num" value="0" onblur="changeNum(this)">
<span class="sub-num" onclick="subNum(this)">-</span>
</div>`;
var td5 = document.createElement("td");
var btnChange = document.createElement("input");
btnChange.type = "button";
btnChange.value = "修改单价";
//修改当前行商品的价格
btnChange.onclick = function () {
var newPrice = prompt("请输入新的单价");
if (newPrice === "" || !newPrice) {
alert("输入为空");
return;
}
var currPrice = this.parentElement.parentElement.children[1];
currPrice.innerHTML = Number(newPrice);
computeMoney();
};
td5.appendChild(btnChange);
var td6 = document.createElement("td");
var btnDelete = document.createElement("input");
//删除当前行的商品
btnDelete.onclick = function () {
this.parentElement.parentElement.remove();
computeMoney();
};
btnDelete.type = "button";
btnDelete.value = "删除商品";
td6.appendChild(btnDelete);
//将td添加到tr上
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
tr.appendChild(td5);
tr.appendChild(td6);
//将添加好的tr返回到函数外面
return tr;
}
//二. 读取数据添加到table中
function printTableInfo() {
var table = document.querySelector("table");
var tbody = table.querySelector("tbody");
for (var i = 0; i < objArr.length; i++) {
var tr = addOneRow(objArr[i]);
//将tr添加到table上
tbody.appendChild(tr);
}
computeMoney();
}
//计算商品的价格
function computeMoney() {
//总价 = 单价 x 数量
//1.获取所有商品的单价
var itemPrices = document.querySelectorAll(".item-money");
//2.所有商品的数量
var itemCounts = document.querySelectorAll(".show-num");
//商品总价
var sumMoney = 0;
//商品总数量
var sumCount = 0;
for (var i = 0; i < itemPrices.length; i++) {
//每个商品的价格和数量
var price = itemPrices[i].innerHTML - 0;
var count = itemCounts[i].value - 0;
sumCount += count;
//每个商品的总价
sumMoney += (price * count);
}
//计算均价 总价/总数量
var avgMoney = (sumMoney / sumCount);
//将获取到的总价和均价添加到页面上
var totalSpan = document.querySelector("#total-money");
var avgSpan = document.querySelector("#avg-money");
totalSpan.innerHTML = sumMoney;
//判断是否每一件商品的数量都为0
if (sumCount === 0) {
avgMoney = 0;
}
avgSpan.innerHTML = avgMoney.toFixed(2);
}
function computeSelectedMoney() {
//1.获取所有商品的单价
var itemPrices = document.querySelectorAll(".item-money");
//2.所有商品的数量
var itemCounts = document.querySelectorAll(".show-num");
//3.所有的商品勾选框
var itemChecks = document.querySelectorAll(".item-check");
//勾选的商品总价
var sumMoney = 0;
for (var i = 0; i < itemPrices.length; i++) {
//每个商品的价格和数量
if (itemChecks[i].checked) {
var price = itemPrices[i].innerHTML - 0;
var count = itemCounts[i].value - 0;
//每个商品的总价
sumMoney += (price * count);
}
}
console.log(sumMoney);
alert("勾选的商品总价为:" + sumMoney + "元");
}
</script>
</html>