You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修正querySelectorAll与forEach结合使用的问题:实现点击加入购物车按钮获取对应商品ID与名称

Fix: Get Correct Product Info on Add to Cart Click

The issue in your code is that document.querySelector() always returns the first matching element in the entire document, regardless of which button you click. To fix this, we need to target elements relative to the clicked button instead of searching the whole page.

Here's the corrected code:

var CartButton = document.querySelectorAll(".eshop_js-add-to-cart");
CartButton.forEach((item) => {
  item.onclick = function () {
    console.log("addToCart works");
    
    // Get the data-id directly from the clicked button
    const productId = this.getAttribute('data-id');
    
    // Find the parent product container relative to the clicked button
    const productContainer = this.closest('.eshop-item-v2-wrap');
    
    // Get the product title from within this specific container
    const productName = productContainer.querySelector('.eshop-item-v2-title').textContent.trim();

    window.dataLayer = window.dataLayer || [];
    dataLayer.push({
      event: 'addToCart',
      ecommerce: {
        add: {
          actionField: { list: 'category' },
          products: [{
            name: productName,
            id: productId,
          }]
        }
      }
    });
    console.log("dataLayer works");
    console.log(`Added product: ${productName} (ID: ${productId})`);
  };
});

Key Changes Explained:

  • this.getAttribute('data-id'): In the click event handler, this refers to the button that was actually clicked, so we get its unique data-id directly instead of grabbing the first button's ID.
  • this.closest('.eshop-item-v2-wrap'): The closest() method travels up the DOM tree from the clicked button to find the nearest parent element with the class .eshop-item-v2-wrap—this is the container that holds both the button and the product title for the item we care about.
  • productContainer.querySelector(...): By calling querySelector on the specific product container instead of the entire document, we ensure we only get the title associated with the clicked button's product.
  • Added .trim() to clean up any extra whitespace in the product title (optional but good practice).

This approach ensures that every "Add to Cart" click captures the correct product ID and name for the item you're interacting with.

内容的提问来源于stack exchange,提问作者Sadi Zeynalov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 08:07:48