修正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,thisrefers to the button that was actually clicked, so we get its uniquedata-iddirectly instead of grabbing the first button's ID.this.closest('.eshop-item-v2-wrap'): Theclosest()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 callingquerySelectoron 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
相关产品推荐
相关产品推荐

