简体   繁体   English

自定义 JS 变量来计算购物车中的商品数量

[英]Custom JS variable to count number of items in cart

My website pushes the following data to the data layer when a purchase is made我的网站在购买时将以下数据推送到数据层

  ecommerce: {
    checkout: {
      actionField: {step: 3, revenue: null},
      products: [
        {
          name: 'Product 1',
          id: 4616,
          price: 516,
          brand: 'Brand Name',
          category: 'Product Type',
          variant: 'Product Version',
          quantity: 1,
          position: 1,
          dimension1: 'Guest',
          dimension2: '',
          dimension3: '',
          metric1: 2
        },
        {
          name: 'Product 2',
          id: 4618,
          price: 400,
          brand: 'Brand Name',
          category: 'Product Type',
          variant: 'Product Version',
          quantity: 1,
          position: 2,
          dimension1: 'Guest',
          dimension2: '',
          dimension3: '',
          metric1: 4
        }
      ]
    }
  }

I want to get the number of items in the basket as a variable in Tag Manager (ie 2 items in cart).我想将购物篮中的商品数量作为跟踪代码管理器中的变量(即购物车中的 2 件商品)。 I'm trying to adjust Dinesh's solution from here that did something similar for total amount, but it's not working for me:我正在尝试从这里调整Dinesh 的解决方案,它对总量做了类似的事情,但它对我不起作用:

function(){
  var productList = ecommerce.checkout.products;
  var totalItems = 0;
  for(var i = 0;i<productList.length;i++)
  {
    totalItems+=(productList[i].quantity);
  }
  return totalItems;
}

Not sure what I'm doing wrong.不知道我做错了什么。

You already have the answer, just find the length of the products which you are already doing in the for loop, that is the number of products in the basket.您已经有了答案,只需在 for 循环中找到您已经在做的产品的长度,即篮子中的产品数量。

Hope i answered your question希望我回答了你的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM