我的目标是构建一个购物车,它能够计算 n
件商品的总价。
我可以增加/减少每件元素的数量,因此一切正常。除了我的 UpdateCartTotal
函数 - 它显示 undefined
而不是总价。我该如何修复它?
function getinput(event) {
return event.target.parentElement.querySelector(".quantity");
}
// the Event Listener
document.addEventListener("click", function(event) {
if (event.target.className == "plus-btn") {
increment(event);
updateCarteTotal(event)
}
if (event.target.className == "minus-btn") {
decrement(event)
updateCarteTotal(event)
}
});
// Increment function
function increment(event) {
var quantity = getinput(event)
if(quantity.value<20){
quantity.value++
}
}
// Decrement function
function decrement(event) {
var quantity = getinput(event)
if(quantity.value >=1){
quantity.value--
}
}
// the function to calculate the totale Carte price
function updateCarteTotal(event) {
const items=document.querySelectorAll(".item");
var total_price=document.querySelector(".total_price");
var quantity=getinput(event);
var unit_price=document.querySelectorAll(".price");
var total=0;
for(item of items ){
total += parseInt(quantity.value * unit_price.value)
}
total_price.value=total.value
}
最佳答案
我看到的主要问题是您试图从原始类型访问不存在的属性。基元类型,例如 number没有像非原始对象一样可以访问的属性,因此:
total += parseInt(quantity.value * unit_price.value)
将不起作用,因为 quantity
没有名为 value
的属性。 unit_price
变量也是如此。出于同样的原因,以下行将不起作用:total_price.value=total.value
。
此外,total_price
的本地作用域为函数 updateCarteTotal
,因此在程序运行期间不会保留值。您最好在任何单个函数的范围之外创建一个全局变量来存储您的购物车总值(value)。
关于javascript - 尝试更改 "total_price"变量的值,但在 Javascript 中得到 "Undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53144130/