[英]Cart delete an item and apply a coupon in js
如果客户有优惠券或超过一定数量,我正在尝试移除商品而不移除购物车并降低价格,而 js 在使用 Django 之前这里是 html 代码 js 如果您有任何建议,请不要犹豫
html
<div data-name="name" data-price="250" data-id="2">
<img src="x.jpg" alt="" />
<h3>name</h3>
<input type="number" class="count" value="1" />
<button class="tiny">Add to cart</button>
</div>
<script type="text/template" id="cartT">
<% _.each(items, function (item) { %> <div class = "panel"> <h3> <%= item.name %> </h3> <span class="label">
<%= item.count %> piece<% if(item.count > 1)
{%>s
<%}%> for <%= item.total %>$</span > </div>
<% }); %>
</script>
js
addItem: function (item) {
if (this.containsItem(item.id) === false) {
this.items.push({
id: item.id,
name: item.name,
price: item.price,
count: item.count,
total: item.price * item.count
});
storage.saveCart(this.items);
} else {
this.updateItem(item);
}
this.total += item.price * item.count;
this.count += item.count;
helpers.updateView();
},
containsItem: function (id) {
if (this.items === undefined) {
return false;
}
for (var i = 0; i < this.items.length; i++) {
var _item = this.items[i];
if (id == _item.id) {
return true;
}
}
return false;
},
updateItem: function (object) {
for (var i = 0; i < this.items.length; i++) {
var _item = this.items[i];
if (object.id === _item.id) {
_item.count = parseInt(object.count) + parseInt(_item.count);
_item.total = parseInt(object.total) +parseInt(_item.total);
this.items[i] = _item;
storage.saveCart(this.items);
}
}
}
您可以使用过滤器 function 删除项目,这样您将仅删除包含特定 ID 的项目。
removeItem(id) {
this.items = this.items.filter(item => item.id !== id);
}
要使用优惠券,除非您的前端存储了所有优惠券,否则您应该拨打 HTTPS 电话以检查优惠券是否有效,以及其价值,然后在购物车中应用折扣。
对您的代码的建议与 containsItem function 相关,您可以在其中迭代整个数组并单独检查每个项目 ID,然后返回给用户。 您可以使用 function 一些让 JS 为您检查。
containsItem: function (id) {
return this.items?.some(item => item.id === id);
}
//PS: the ?. is a notion that checks if the variable exists and if it's true it continues, that way you won't have an undefined error. It is called [Optional Chaining][2]
另一个建议是关于 updateItem,您可以通过查找function 获得所需的元素。
updateItem: function (object) {
const itemToUpdate = this.items.find(item => item.id === object.id);
if(itemToUpdate) {
itemToUpdate.count = parseInt(object.count) + parseInt(itemToUpdate.count);
itemToUpdate.total = parseInt(object.total) +parseInt(itemToUpdate.total);
storage.saveCart(this.items);
}
}
此外,您不需要重新分配数组,因为当您引用 object 时,它的源代码也会更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.