DOM操作实例 购物车 (3)

//直接修改数字
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>
<span>+</span>
<input type="text" value="0" onblur="changeNum(this)">
<span>-</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();
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwfzgs.html