DOM操作实例 购物车 (2)

//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();
}

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

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