簡體   English   中英

如何用JavaScript制作購物車

[英]how to make a shopping cart in javascript

我在使用Javascript制作項目的購物車時遇到麻煩。 我制作了名為“添加到購物車”的按鈕,並嘗試了各種方法,以便在單擊按鈕時將產品的名稱和價格添加到購物車中。 我嘗試了按鈕onclick,但是它不起作用。 我嘗試了addEventListener,但由於某種原因未單擊按鈕時,它會顯示產品信息。 我該如何做,以便當我單擊按鈕時,它可以在購物車中顯示產品信息? 另外,我該如何創建元素div(我在下面注釋掉的代碼)?

我也不知道如何在購物車上顯示產品圖片。

  var shoppingCart = []; function addToCart(title, price) { var product = {}; product.title = title; product.price = price; shoppingCart.push(product); displayShoppingCart(); } function displayShoppingCart() { var totalPrice = 0; var displayTitle = document.getElementById("displayTitle"); var displayPrice = document.getElementById("displayPrice"; for (var product in shoppingCart) { displayTitle.innerHTML = shoppingCart[product].title; displayPrice.innerHTML = shoppingCart[product].price; // title.createElement('div'); // div.className = "itemTitle"; // itemTitle = document.querySelectorAll(".itemTitle"); // itemTitle.innerHTML = shoppingCart[product].title; } } var book1 = document.getElementById("book1"); book1.addEventListener("click", addToCart("Cracking the Coding Interview","$29.99")); 
  <button class="addcart" id="book1" onclick="addToCart("Cracking the Coding Interview", "$29.99")"> Add to Cart </button> <div id="displayTitle"></div> <div id="displayPrice"></div> 

這是基本的購物車,您可以在文本框中輸入標題和價格(僅數字,不允許輸入字符),然后單擊按鈕將添加到購物車中。

 var product=[]; function fun(){ var x={}; x.price=document.getElementById('price').value; x.title=document.getElementById('title').value; product.push(x); var iDiv = document.createElement('div'); iDiv.id = product.length; iDiv.className = 'block'; document.getElementsByTagName('body')[0].appendChild(iDiv); var para = document.createElement("span"); var node = document.createTextNode('Title: ' + x.title+' | '); para.appendChild(node); var element = document.getElementById(product.length); element.appendChild(para); para = document.createElement("span"); node = document.createTextNode('Price: '+ x.price); para.appendChild(node); element.appendChild(para); } 
 Title:<input id="title" type="text"> Price:<input id="price" type="number"> <button onClick="fun()">Add to Cart </button> <div> <p><b>Cart Info</b></p> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM