繁体   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