在用户的大力帮助下:PSL我已经在购买了购物车的项目中途。 但是,我还想为不同的产品添加价格,并将它们全部加入 div =“sum”。
我可以为包含价格的产品添加另一个属性并循环并总结总数??
http://jsfiddle.net/bald1/Tw9L9/
var cart = [];
var cartElement = document.getElementById("cart");
function addToCart(productName) {
cart.push(productName);
cartElement.innerHTML = cart.join("<br>");
}
var products = document.getElementsByClassName('details');
for(var i=0; i < products.length; i++){
products[i].addEventListener("click", handleClick, false);
}
function handleClick(e){
var str = this.dataset.productname;
addToCart(str);
}
答案 0 :(得分:0)
尝试这样的事情,FIDDLE
javascript代码
var cart = [];
var cartElement = document.getElementById("cart");
function addToCart(obj) {
var str = obj.dataset.productname;
var price = obj.dataset.price;
cart.push(str);
cartElement.innerHTML = cart.join("<br>");
var old_price = document.getElementById('total_sum').value;
var new_price = parseInt(old_price) + parseInt(price);
document.getElementById('total_sum').value = new_price;
document.getElementById('sum').innerHTML = new_price;
}
var products = document.getElementsByClassName('details');
for (var i = 0; i < products.length; i++) {
products[i].addEventListener("click", handleClick, false);
}
function handleClick(e) {
addToCart(this);
}
HTML CODE
<div id="cart"></div>
<div class="item">
<div class="wrapper">
<img src="images.png" alt="">
</div>
<p class="details" data-productName="prod1" data-price="100">prod</p>
</div>
<div class="item">
<div class="wrapper">
<img src="images.png" alt="">
</div>
<p class="details" data-productName="prod2" data-price="200">prod2</p>
</div>
<div id="sum">
<p>SUM</p>
</div>
<input type="hidden" id="total_sum" value="0" />