如何添加项目而不是仅仅粘贴它



const Sheet = [
{
"Code": "A-0-1", 
"UPC": "Photos/4009803054728.jpg",
"Title": "U.S.S. Constitution",
"Price": "$34",
"InStock": "7"
},
]

const productsEl = document.querySelector(".Sheet");
function getProducts() {
Sheet.forEach((product) => {
productsEl.innerHTML += `<div class="productContainer">
<div class="img">
<img src=${product.UPC} alt="Image Unavailable" height="170px;" width="170px">
</div>
<div class="itemdesc">
<h2 class="itemName" id="itemName">${product.Title}</h2>
<h4 class="price"><span id="price">${product.Price}</span></h4>
<div class="desc">
<p id="desc">${product.Code}</p>
</div>
<div class="stock">
<p> ${product.InStock} Units</p>
</div>
<div class="addToCart" onclick="addToCart(this);">
<button id="addToCart" > Add to Cart</button>
</div>
</div>`; 
})
}
getProducts(); 
let numUnit = document.getElementById("#Unit")
let itemTitle = document.getElementById("item")
let itemPrice = document.getElementById("$Price")
function addToCart(button) {
const parent = button.closest('.productContainer'),
Title = parent.querySelector('#itemName')
Price = parent.querySelector('#price')
Code = parent.querySelector('#desc')
itemTitle.textContent = Title.innerText + ' ' + Code.innerText
itemPrice.textContent = Price.innerText

//let itemInput = document.createElement('input')
//itemInput.value = numUnit.innerText
numUnit.textContent = '1'
}
<div class="itemUl">
<ul>
<li id="Units">Units:<span id="#Unit"></span></li>
<li id="Items">Item:<span id="item"></span></li>
<li id="Price">Price:<span id="$Price"></span></li>
</ul>
</div>
</div>
<div class="Sheet">
</div>

为了添加任务而不是仅仅将其粘贴到购物车中,我可以更改什么?目前,我将它添加到我的购物车中,但如果按下另一个对象,它会替换它而不是添加它。顺便说一下,我的"工作表"里有很多对象为了节省空间,我只写了一个。

您可以做的是创建一个<Component />,并将Sheet[]中的项目附加到您的.Sheet元素中。

<<p>CartItem组件/strong>
function CartItem({ code, UPC, title, price, inStock } = {}) {
const card = document.createElement('div')
card.classList.add('card')
const cardImg = document.createElement('img')
cardImg.classList.add('card-img')
cardImg.src = UPC
const cardBody = document.createElement('div')
cardBody.classList.add('card-body')
const cardTitle = document.createElement('h2')
cardTitle.classList.add('card-title')
cardTitle.innerText = title
const cardText = document.createElement('h2')
cardText.classList.add('card-text')
cardText.innerText = price
const cardDesc = document.createElement('card-desc')
cardDesc.classList.add('card-desc')
cardDesc.innerText = code
const cardSticker = document.createElement('card-sticker')
cardSticker.classList.add('card-sticker')
cardSticker.innerText = inStock

cardBody.append(cardTitle, cardText, cardDesc, cardSticker)
card.append(cardImg, cardBody)
return card
}

,然后使用

Sheet.map((item) => {
productsEl.appendChild(CartItem({...item}))
})

相关内容

  • 没有找到相关文章

最新更新