Question:
1. When the page is opened for the first time, since there is no local storage, the data will not be retrieved. The product will be added by 1 and will not be added to the shopping cart. However, 1 will be added and 2 items will be added to the shopping cart at once. Lesson normal addition and subtraction
2. When adding the first item of each product, it will not be added to the shopping cart when the second item is added.
Display effect: https://ityanxi.github.io/seg...
Code address: https://github.com/ityanxi/se...
js code:
//獲取元素
function $(id){
return document.getElementById(id);
}
var table =$('cartTable'); // 購(gòu)物車(chē)表格
var tr = table.children[1].rows; //行
var priceTotal = $('priceTotal'); //總計(jì)
var selectedTotal =$('selectedTotal'); //已選商品數(shù)目容器
var selectedViewList = $('selectedViewList'); //浮層已選商品列表容器
var foot = $('foot');
utils = {
setParam : function (name,value){ //存儲(chǔ)數(shù)據(jù)
localStorage.setItem(name,value)
},
getParam : function(name){ //獲取數(shù)據(jù)
return localStorage.getItem(name)
}
}
product={
name:"",
num:0,
price:0.00,
};
orderdetail={
username:"",
phone:"",
address:"",
zipcode:"",
totalNumber:0,
totalAmount:0.00
}
cart = {
//向購(gòu)物車(chē)中添加商品
addproduct: function (product) {
var ShoppingCart = utils.getParam("ShoppingCart"); //獲取數(shù)據(jù)
if (ShoppingCart == null || ShoppingCart == "") {
//第一次加入商品
var jsonstr = { "productlist": [{
"name": product.name, //商品名稱
"num": product.num, //商品數(shù)量
"price": product.price}], //商品單價(jià)
"totalNumber": product.num, //單一商品總數(shù)
"totalAmount": (product.price * product.num) //商品總價(jià)
};
//JSON.stringify(jsonstr) //將json對(duì)象轉(zhuǎn)換成字符串.
utils.setParam("ShoppingCart", "'" + JSON.stringify(jsonstr)); //存儲(chǔ)數(shù)據(jù)
} else {
//JSON.parse(ShoppingCart.substr(1, ShoppingCart.length))//對(duì)json數(shù)據(jù)的解釋 將字符串變成json對(duì)象
var jsonstr = JSON.parse(ShoppingCart.substr(1, ShoppingCart.length));
var productlist = jsonstr.productlist;
var result = false;
//查找購(gòu)物車(chē)中是否有該商品
for (var i in productlist) {
if (productlist[i].name == product.name) {
productlist[i].num = parseInt(productlist[i].num) + parseInt(product.num);
result = true;
}
}
if (!result) {
//沒(méi)有該商品就直接加進(jìn)去
productlist.push({"name": product.name, "num": product.num, "price": product.price });
}
//重新計(jì)算總價(jià)
jsonstr.totalNumber = parseInt(jsonstr.totalNumber) + parseInt(product.num);
jsonstr.totalAmount = parseFloat(jsonstr.totalAmount) + (parseInt(product.num) * parseFloat(product.price));
//保存購(gòu)物車(chē)
utils.setParam("ShoppingCart", "'" + JSON.stringify(jsonstr));
}
},
//修改給買(mǎi)商品數(shù)量
updateproductnum: function (name, num) {
console.log(name,'+++:',num);
var ShoppingCart = utils.getParam("ShoppingCart");
var jsonstr = JSON.parse(ShoppingCart.substr(1, ShoppingCart.length));
console.log(jsonstr);
var productlist = jsonstr.productlist;
for (var i in productlist) {
if (productlist[i].name == name) {
jsonstr.totalNumber = parseInt(jsonstr.totalNumber) + (parseInt(num) - parseInt(productlist[i].num));
console.log(parseInt(jsonstr.totalNumber),parseInt(productlist[i].num));
jsonstr.totalAmount = parseFloat(jsonstr.totalAmount) + ((parseInt(num) * parseFloat(productlist[i].price)) - parseInt(productlist[i].num) * parseFloat(productlist[i].price));
productlist[i].num = parseInt(num);
orderdetail.totalNumber = jsonstr.totalNumber;
orderdetail.totalAmount = jsonstr.totalAmount;
selectedTotal.innerHTML= orderdetail.totalNumber;
priceTotal.innerHTML=(orderdetail.totalAmount).toFixed(2);//保留兩位小數(shù)
utils.setParam("ShoppingCart", "'" + JSON.stringify(jsonstr));
console.log("'"+ JSON.stringify(jsonstr))
return;
}
}
},
//獲取購(gòu)物車(chē)中的所有商品
getproductlist: function () {
var ShoppingCart = utils.getParam("ShoppingCart");
var jsonstr = JSON.parse(ShoppingCart.substr(1, ShoppingCart.length));
var productlist = jsonstr.productlist;
orderdetail.totalNumber = jsonstr.totalNumber;
orderdetail.totalAmount = jsonstr.totalAmount;
return productlist;
},
//判斷購(gòu)物車(chē)中是否存在商品
existproduct: function (name) {
var result = false;
var ShoppingCart = utils.getParam("ShoppingCart");
if (ShoppingCart != null) {
var jsonstr = JSON.parse(ShoppingCart.substr(1, ShoppingCart.length));
var productlist = jsonstr.productlist;
for (var i in productlist) {
if (productlist[i].name == name) {
result = true;
}
}
}
return result;
},
//刪除購(gòu)物車(chē)中商品
deleteproduct: function (name) {
var ShoppingCart = utils.getParam("ShoppingCart");
var jsonstr = JSON.parse(ShoppingCart.substr(1, ShoppingCart.length));
var productlist = jsonstr.productlist;
var list = [];
for (var i in productlist) {
if (productlist[i].name == name) {
jsonstr.totalNumber = parseInt(jsonstr.totalNumber) - parseInt(productlist[i].num);
jsonstr.totalAmount = parseFloat(jsonstr.totalAmount) - parseInt(productlist[i].num) * parseFloat(productlist[i].price);
} else {
list.push(productlist[i]);
}
}
jsonstr.productlist = list;
orderdetail.totalNumber = jsonstr.totalNumber;
orderdetail.totalAmount = jsonstr.totalAmount;
utils.setParam("ShoppingCart", "'" + JSON.stringify(jsonstr));
}
};
loadData()
//加載數(shù)據(jù)
function loadData(){
if(localStorage.length>0){//如果有存儲(chǔ)數(shù)據(jù) 則獲取并渲染
var productlist=cart.getproductlist();//取出購(gòu)物車(chē)商品
var countInput = table.getElementsByClassName('count-input'); //數(shù)目input
var goods=table.getElementsByClassName('goods');
var names=[];
for(var i=0;i<goods.length;i++){
//console.log(goods[i].children[1].innerHTML);
names.push(goods[i].children[1].innerHTML);
}
//var names=goods.children[1];
//console.log(productlist);
//console.log(names);
for(var i=0;i<names.length;i++){
for(var j=0;j<productlist.length;j++){
if(names[i]==productlist[j].name){
//console.log(i)
countInput[i].value=productlist[j].num
}
}
}
for(var i=0;i<productlist.length;i++){
console.log(productlist[i]);
var str=' 名稱:'+productlist[i].name+' 數(shù)量:'+productlist[i].num+' 小計(jì):'+(parseInt(product.num) * parseFloat(product.price))
console.log(str);
}
selectedTotal.innerHTML= orderdetail.totalNumber;
priceTotal.innerHTML=(orderdetail.totalAmount).toFixed(2);//保留兩位小數(shù)
}else{
return
}
}
//為每行元素添加事件
for (var i = 0; i < tr.length; i++) {
//將點(diǎn)擊事件綁定到tr元素
tr[i].onclick = function (e) {
var e = e || window.event;
var el = e.target || e.srcElement; //通過(guò)事件對(duì)象的target屬性獲取觸發(fā)元素
var cls = el.className; //觸發(fā)元素的class
var countInout = this.getElementsByTagName('input')[0]; // 數(shù)目input
var value = parseInt(countInout.value); //數(shù)目
var goods=this.getElementsByClassName('goods')[0];
var name=goods.children[1].innerHTML;
var price=this.getElementsByClassName('price')[0].innerHTML;
//通過(guò)判斷觸發(fā)元素的class確定用戶點(diǎn)擊了哪個(gè)元素
switch (cls) {
case 'add': //點(diǎn)擊了加號(hào)
countInout.value = value + 1;
break;
case 'reduce': //點(diǎn)擊了減號(hào)
if (value > 0) {
countInout.value = value - 1;
}
break;
}
var product =
{
//屬性名用引號(hào)括起來(lái),屬性間由逗號(hào)隔開(kāi)
'name': name,
'num':countInout.value,
'price':price
};
console.log(product.num);
if(cart.existproduct(product.name)){
cart.updateproductnum(product.name,product.num);
}else{
cart.addproduct(product)
}
//loadData()
}
}
function remove1(){
localStorage.removeItem("ShoppingCart")//刪除變量名為key的存儲(chǔ)變量
}
擁有18年軟件開(kāi)發(fā)和IT教學(xué)經(jīng)驗(yàn)。曾任多家上市公司技術(shù)總監(jiān)、架構(gòu)師、項(xiàng)目經(jīng)理、高級(jí)軟件工程師等職務(wù)。 網(wǎng)絡(luò)人氣名人講師,...
Give me an idea. After the page is loaded, determine whether the products that have not been entered into the shopping cart need to be added to localstorage. If the value is set to 0, it will not be displayed.
It doesn’t work for the first time, but it works for the second time. Try printing information between the two times to see where the problem is. Adding a judgment can basically solve it. If it doesn’t work, you can judge whether it is the first time.