我希望购物车添加与Add to cart
按钮相关的项目。您能否也解释一下其不起作用的原因。目前,它仅添加第一个产品。
这是HTML:
<p class="name">Playstation 4 console (Black)</p>
<p class="pricetitle">Price: <span id="price">1899</span> AED</p>
<form>
<button type="button" onclick="addToCart()">Add to cart</button>
</form>
<p class="name">Xbox one console (Black)</p>
<p class="pricetitle">Price: <span id="price">1800</span> AED</p>
<form>
<button type="button" onclick="addToCart()">Add to cart</button>
</form>
这是JavaScript:
const name = document.querySelectorAll(".name");
const price = document.querySelectorAll("#price");
const button = document.querySelectorAll("button");
const cart = []
const addToCart = () => {
for (var i = 0; i < 1; i++) {
cart.push(name[i].innerText)
cart.push(parseInt(price[i].innerText))
}
console.log(cart)
}
谢谢
答案 0 :(得分:0)
这里是一个示例,其中我们在html中使用data-
属性。为了在装车时为我们提供帮助。
let buttons = document.getElementsByTagName("button");
const cart = [];
for(var i=0; i<buttons.length; i++) {
let button = buttons[i];
console.log(button);
button.addEventListener('click', function(event){
console.clear();
console.log(event.target);
console.log(event.target.dataset.productSku);
cart.push( event.target.dataset.productSku );
console.log(cart)
});
}
<p class="name">Playstation 4 console (Black)</p>
<p class="pricetitle">Price: <span id="price">1899</span> AED</p>
<button data-product-sku="ps4black">Add to cart</button>
<p class="name">Xbox one console (Black)</p>
<p class="pricetitle">Price: <span id="price">1800</span> AED</p>
<button data-product-sku="xboxoneblack">Add to cart</button>
<div id="cart"></div>