如何在javascript中制作购物车

问题描述 投票:-1回答:1

我在使用Javascript为项目制作购物车时遇到了麻烦。我制作了名为Add to Cart的按钮,我尝试了各种方法,以便当我点击按钮时,我将产品的名称和价格添加到购物车。我试过按钮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>
javascript cart shopping
1个回答
2
投票

这是一个基本的购物车,你在文本框和价格中键入标题(它只是数字,不允许字符),点击按钮项目将被添加到购物车。

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>
© www.soinside.com 2019 - 2024. All rights reserved.