我目前正在开发一个web应用程序,该应用程序稍后将作为某种网络商店使用。我现在正在开发一个addToCart函数,它必须从点击的元素中选取某些数据(产品的名称和价格,然后将1加到pcs中并将所有内容保存到会话中),然后将这2个值粘贴到我制作的模板中,并将带有值的模板放到shopCart中。
这是我为加载所有产品而编写的当前javascript代码,我试图显示当时单击的项目的一些值:
$(function(){
$.getJSON("assets/products/sample_products.json", function(response) {
$.each(response.data, function (i, el) {
let card = $($('#productCard-template').html());
card.find('#cardName').html( el.name);
card.find('#cardPrice').html( '€' + el.price );
card.find('.productItem').attr('data-price', el.price)
.attr('data-article-number', el.article_number)
.attr('data-id', el.id)
.attr('data-name', el.name)
.attr('data-stock', el.stock)
.attr('data-categories', el.categories);
$('#touchViewProducts').append(card);
});
});
});
//onclick function adds data of product to the designated template
function addToCart(){
var value = document.getElementById("productCard").value;
var getDataVal = document.getElementById('productCard-template').getAttribute('data-name', 'data-price');
var total = 0;
console.log(this.data-name)
}这是模板的html代码:
<script type="text/template" id="productCard-template">
<div class="col-3 productCard" id="productCard" onclick="addToCart()">
<a href="#" class="productItem">
<div class="card">
<img src="assets/images/Firecracker.jpg" alt="Avatar" style="width: 100%; height: 8vh;">
<div class="container">
<div class="row" style="height: 6vh; max-width: 20ch;">
<p id="cardName"> </p>
</div>
<div class="row" style="height: 50%">
<b><p id="cardPrice"></p></b>
</div>
</div>
</div>
</a>
</div>
</script>
<script type="text/template" id="shopcartRow-template">
<div class="row">
<div class="col-5" id="valueName"> </div>
<div class="col-1" id="valueQty"> </div>
<div class="col-2" id="valuePrice"> </div>
<div class="col-3" id="valueTotal"> </div>
</div>
</script>这是一个图像的网页应用程序看起来像,当点击卡片上包含“奥斯卡和价格89",我想把它的功能添加到购物车与产品”奥斯卡“,个人电脑。1 (pcs += 1),价格"89“,总数也是"89”
发布于 2020-09-28 19:48:39
因为列表中每个条目都有一系列data-*属性(具有id、name、…)我认为最简单的方法是创建一个item对象(基于这些data-*属性)并将其添加到购物车类中。
Cart类将有一个Items属性,其中将存储图表的内容。项目应该是一个Map(),这将有助于管理重复,删除项目等。
以下是Chart的代码示例,说明如何添加项目以及如何计算购物车的价格。
class Cart {
constructor() {
this.items = new Map();
}
get price() {
return [...this.items.values()].reduce((price, item) => price += item.price, 0);
}
}
const cart = new Cart();
// this would be inside addToCart() funtion. Values would be retrived thanks to data-*
cart.items.set(1, {
price: 100,
name: 'shoes'
});
cart.items.set(2, {
price: 30,
name: 'socks'
});
console.log(cart.price)https://stackoverflow.com/questions/64099990
复制相似问题