【问题标题】:Attempting to change value of "total_price" variable but am getting "Undefined" in Javascript试图更改“total_price”变量的值,但在 Javascript 中得到“未定义”
【发布时间】:2018-11-04 18:39:55
【问题描述】:

我的目标是构建一个购物车,它能够计算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
    }

【问题讨论】:

    标签: javascript math increment decrement


    【解决方案1】:

    我看到的主要问题是您试图从原始类型访问不存在的属性。 number 等基元类型没有像非基元对象那样可以访问的属性,因此:

    total += parseInt(quantity.value * unit_price.value) 将不起作用,因为 quantity 没有名为 value 的属性。 unit_price 变量也可以这样说。出于同样的原因,以下行将不起作用:total_price.value=total.value

    此外,total_price 的作用域是函数 updateCarteTotal,因此它不会在程序运行期间保留值。您最好在任何单个函数的范围之外创建一个全局变量来存储您的购物车总价值。

    【讨论】:

      猜你喜欢
      • 2018-08-06
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多