场景:
问题:
以下功能将在用户单击增加或减少符号时更改项目的数量
document.body.addEventListener("click", function(e) {
var reg = /\w{7}\d+/g;
if (e.target.classList[0] === "increaseQty") {
var getItem = getLocalStorageData("basketData");
getItem.basketQty++;
document.getElementById("item-count").innerHTML = getItem.basketQty;
e.target.previousSibling.value++;
var currentProduct = e.target.previousSibling.id;
currentProduct = currentProduct.match(reg);
currentProduct = currentProduct.toString();
getItem[currentProduct]++;
updateLocalStorage(getItem);
for (var i = 0; i < productCats.length; i++) {
if (productCats[i][currentProduct]) {
var currentPrice = e.target.previousSibling.value * productCats[i][currentProduct].price;
var currentLi = e.target.parentNode;
currentLi.parentNode.lastChild.innerHTML = "£" + currentPrice;
getTotalCost();
}
}
} else if (e.target.classList[0] === "decreaseQty") {
if (e.target.nextSibling.value > 0)
var getItem = getLocalStorageData("basketData");
getItem.basketQty--;
document.getElementById("item-count").innerHTML = getItem.basketQty;
e.target.nextSibling.value--;
var currentProduct = e.target.nextSibling.id;
currentProduct = currentProduct.match(reg);
currentProduct = currentProduct.toString();
getItem[currentProduct]--;
updateLocalStorage(getItem);
for (var i = 0; i < productCats.length; i++) {
if (productCats[i][currentProduct]) {
var currentPrice = e.target.nextSibling.value * productCats[i][currentProduct].price;
var currentLi = e.target.parentNode;
currentLi.parentNode.lastChild.innerHTML = "£" + currentPrice;
getTotalCost();
}
}
} else {
return;
}
})
$("#basket-content").on("change", 'input[name="nameQty"]', function() {
var getItem = getLocalStorageData("basketData");
var regNum = /\d+/;
var currentQty = this.id;
var currentVal = this.value;
var reg = /\w{7}\d+/g;
var product = currentQty.match(reg);
product = product.toString();
if (!regNum.test(currentVal) || currentVal < 0) {
alert("Please enter a valid number");
document.getElementById(currentQty).value = getItem[product];
return;
} else if (currentVal > getItem[product]) {
var addQty = currentVal - getItem[product];
getItem.basketQty += addQty;
document.getElementById("item-count").innerHTML = getItem.basketQty;
getItem[product] = currentVal;
} else if (currentVal < getItem[product]) {
var minusQty = getItem[product] - currentVal;
getItem.basketQty -= minusQty;
document.getElementById("item-count").innerHTML = getItem.basketQty;
getItem[product] = currentVal;
}
for (var i = 0; i < productCats.length; i++) {
if (productCats[i][product]) {
var currentPrice = currentVal * productCats[i][product].price;
document.getElementById(currentQty).parentNode.nextSibling.innerText = "£" + currentPrice.toFixed(2);
getTotalCost();
}
}
updateLocalStorage(getItem);
});