1 回答
TA贡献1862条经验 获得超7个赞
你可能想要这个
const cart = document.getElementById("cart");
const productName = document.querySelectorAll(".product-name");
const productPrice = document.querySelector(".product-price");
const addBtn = document.querySelectorAll(".add");
addBtn.forEach(button => {
button.addEventListener("click", addToCart);
})
//Add to cart
function addToCart(e) {
e.preventDefault();
//Create DIV
const item = document.createElement("div");
item.classList.add("item");
//Add name
const name = document.createElement("h2");
name.classList.add("product-name");
name.innerText = e.target.parentNode.querySelector(".product-name").innerText;
item.appendChild(name);
cart.appendChild(item);
}
<div class="product">
<h2 class="product-name">Beer</h2>
<h3 class="product-price">$4</h3>
<button class="add">Add to cart</button>
</div>
<div id="cart"></div>
委派对产品的点击
const cart = document.getElementById("cart");
const products = document.getElementById("products");
const productName = document.querySelectorAll(".product-name");
const productPrice = document.querySelector(".product-price");
products.addEventListener("click", addToCart);
//Add to cart
function addToCart(e) {
e.preventDefault();
const tgt = e.target;
if (!tgt.classList.contains("add")) return; // not a button
const parent = tgt.parentNode;
//Create DIV
const item = document.createElement("div");
item.classList.add("item");
//Add name
const name = document.createElement("h2");
name.classList.add("product-name");
name.innerText = parent.querySelector(".product-name").innerText;
item.appendChild(name);
cart.appendChild(item);
}
<div id="products">
<div class=" product ">
<h2 class="product-name ">Beer</h2>
<h3 class="product-price ">$4</h3>
<button class="add ">Add to cart</button>
</div>
<div class="product ">
<h2 class="product-name ">Wine</h2>
<h3 class="product-price ">$4</h3>
<button class="add ">Add to cart</button>
</div>
</div>
<div id="cart"></div>
添加回答
举报