Native js implements shopping cart logic and functions
- 2021-11-24 00:42:02
- OfStack
This article example for everyone to share the js shopping cart logic and function of the specific code, for your reference, the specific content is as follows
1. The main content layout of the shopping cart should try to use the table layout mode
2. Judge whether the user logs in or not
The code is as follows, which can be modified according to the layout of your header
// Judge whether the user logs in or not
var username = getCookie("username");
// Execute this code if the login is successful
if(username){
var vip = $(`<a href='javascript:;'> Welcome <b>${username}</b> Come to Tmall Supermarket </a>`)
var loginout = $(`<a href='javascript:;' class="loginout"> Quit </a>`)
$(".hLeft").empty()
$(".hLeft").append(vip)
$(".hLeft").append(loginout)
$(".hLeft>a").css({
"color":"#666",
"lineHeight":"32px",
"marginLeft":"10px"
})
$(".hLeft>a>b").css({
"color":"red",
"fontWeight":"800",
})
$(".loginout").click(function(){
removeCookie("username")
$(".hLeft").empty()
$(".hLeft").html(` <a href="home.html" > Tmall homepage </a>
<a href="javascript:;" > Meow, welcome to Tmall </a>
<a href="login.html" > Please log in </a>
<a href="register-test.html" > Free registration </a>`)
})
}else{
alert(" Please log in first ");
location.assign("./login.html");
}
3. Judge whether there is data transmitted from the details page
Here, my data is stored in local storage, and you can get the data according to your own storage place
The code is as follows:
// Receive data from the details page
// First judge whether there are goods in local storage
var data = localStorage.getItem("cart");
if(!data){
$(".page-con").empty();
var str = "";
str +=`<h2> The shopping cart is empty! ! ! </h2>
<p> Please quickly move to the list page and select the items <p><a href="./list.html" > Enter the list page </a>
`
$(".page-con").html(str);
$(".page-con").css({width:"900px",margin:"40px auto 0"});
$(".page-con h2").css({fontSize:"50px",color:"blue",lineHeight:"80px"})
$(".page-con p").css({fontSize:"20px",lineHeight:"26px"});
$(".page-con a").css({width:"100px",height:"40px",background:"skyblue",marginTop:"20px",display:"block"})
}else{
// Then judge whether the shopping cart of the current user is data
// Convert data to array type
data = JSON.parse(data);
// To see if data exists
for(var j=0;j<data.length;j++){}
var res = data.some(v=>{
return v.username == username;
})
if(!res){
$(".page-con").empty();
var str = "";
str +=`<h2> The shopping cart is empty! ! ! </h2>
<p> Please quickly move to the list page and select the items <p><a href="./list.html" > Enter the list page </a>
`
$(".page-con").html(str);
$(".page-con").css({width:"900px",margin:"40px auto 0"});
$(".page-con h2").css({fontSize:"50px",color:"blue",lineHeight:"80px"})
$(".page-con p").css({fontSize:"20px",lineHeight:"26px"});
$(".page-con a").css({width:"100px",height:"40px",background:"skyblue",marginTop:"20px",display:"block"})
}else{
// Have data And have their own data
// Find out your own data first
var arr = data.filter(v=>v.username == username);
// Traversing the acquired data
// There is no desired commodity data in the array, which needs to be obtained from the database 1 Under Pass id Find data in a database
var ids = arr.map(v=>v.goodsid);
ids = ids.join(",")
4. When querying the data transmitted from the details page, we can find the data we want in the database through the transmitted id
Send ajax to the database to find the information of goods
$.ajax({
url:"./server/cart.php",
dataType:"json",
data:{ids:ids},
type:"get",
success:res=>{
var str = '';
for(var i=0;i<res.length;i++){
// According to res[i] Every 1 Articles, from arr Find out in number Quantity
var number = arr.find(v=>v.goodsid==res[i].id).number;
str +=`
<div class="pageMtop">
<input type="checkbox" name="onetop"><i></i><span> Shop: ${res[i].name}</span><em></em>
</div>
<div class="pageMcontent">
<h3><img src="images/cat10.png">8.6 0 Enjoy by clicking , Every full 300 Minus 30</h3>
<ul>
<li>
<input type="checkbox" name="one">
</li>
<li>
<a href="#" >
<img src="${res[i].imgpath}">
</a>
</li>
<li>
<p>
<a href="#" >${res[i].introduce}</a>
</p>
<img src="images/cat03.png" alt="">
<a href="javascript:;" ><img src="images/cat04.png" alt=""></a>
</li>
<li>
<p> Size: M</p>
<p> Main color: 6685 White +6691 Haze blue ( M Code pre-sale 8 Month 8 Number issued </p>
<a href="#" > Modify </a>
</li>
<li>
<span>${res[i].price}</span>
</li>
<li class="data-name" data-id = "${res[i].id}">
<input type="button" class="reduce" value="-">
<input class="numberone" type="number" name="number" data-stock="${res[i].stock}" value="${number}">
<input type="button" class="add" value="+">
</li>
<li class="subtotal">
${res[i].price*number}
</li>
<li>
<p> Move into a folder </p>
<p class="btn"> Delete </p>
<p> Baby </p>
</li>
</ul>
</div>
`
}
$(".page-middle").html(str)
// Add the Select All feature here
// Words written here Code nested too deeply - Write the function outside, and then call the function here
// Invoke all selected functions
selectAll()
// Call radio function
selectone()
// Calculate the total price and quantity
priceAndNumberAll()
// Quantity addition and subtraction
addAndReduce()
// Click the Delete button
removebtn()
}
})
}
Here, we need to dynamically load the layout and content rendering of the product column, and then add it to the big box where the main content is placed
5. Realize the function of shopping cart page
Because there are many functional codes, they will appear redundant when placed in ajax. We encapsulate each function into a function and call it directly in the callback function after ajax is completed
6. All selection function
The code is as follows:
// All selection function
function selectAll(){
// Bind events to the upper and lower all selections
$("[name='topAll']")[0].onclick = $("[name='footAll']")[0].onclick = function(){
// Set the status of radio selection
$("[name='one']").prop("checked",$(this).prop("checked"))
$("[name='onetop']").prop("checked",$(this).prop("checked"))
// Add Select All to both check boxes
$("[name='topAll']").prop("checked",$(this).prop("checked"))
$("[name='footAll']").prop("checked",$(this).prop("checked"))
priceAndNumberAll()
}
}
7. Radio function
The code is as follows:
// Single selection function
function selectone(){
$("[name='one']").click(function(){
// Determine if all are selected
//$("[name='one']") Yes 1 Pseudo array, array method cannot be called Turn it into an array first
$("[name='onetop']").prop("checked",$(this).prop("checked"))
var arr = Array.prototype.slice.call($("[name='one']"))
// Call every Method If there is 1 Return if you don't select false
var res = arr.every(v=>$(v).prop("checked"));
if(res){
$("[name='topAll']").prop("checked","checked");
$("[name='onetop']").prop("checked","checked");
$("[name='footAll']").prop("checked","checked");
}else{
$("[name='topAll']").prop("checked",false);
$("[name='footAll']").prop("checked",false)
}
priceAndNumberAll()
})
}
8. Calculate the total quantity and the total price
The code is as follows:
// Calculate the total price and quantity
function priceAndNumberAll(){
// Calculate according to the selected box
// Select the selected quantity number
var allNumInput = $("[name='one']:checked").parent().siblings(".data-name").find("[name='number']")
var allNum = 0;
allNumInput.each(function(k,v){
allNum += v.value-0;
})
$(".allnumber").text(allNum);
var allPriceEle = $("[name=one]:checked").parent().siblings(".subtotal")
var allPrice = 0;
allPriceEle.each(function(k,v){
allPrice += allPriceEle.text()-0;
})
$(".allprice").text(allPrice);
}
9. Click the Add and Subtract button to add and subtract the quantity and amount
The code is as follows:
// Click the addition and subtraction quantity to add and subtract
function addAndReduce(){
// Click the Add button
$(".add").click(function(){
// Get first input The value in the box
var num = $(this).prev().val()-0;
// Per click 1 Give way every time input The value inside ++
num ++
// Data cannot be added wirelessly To make a judgment If added to the maximum value I won't let him add it
if(num>=$(this).prev().attr("data-stock")-0){
num=$(this).prev().attr("data-stock")-0
$(this).prop("disabled",true);
$(this).addClass("bgadd");
$(this).prev().prev().prop("disabled",false);
}else{
$(this).prop("disabled",false);
$(this).prev().prev().removeClass("bgreduce");
}
$(this).prev().val(num)
// Calculate the price in subtotal
// Find the label and value where the unit price is placed
var price = $(this).parent().prev().find("span").text()-0;
// Recalculate subtotal
var subtotal = price*num;
// After calculating the subtotal, put it in the storage one td Medium
$(this).parent().next().text(subtotal);
// Reset local storage
// Getting locally stored data
var data = localStorage.getItem("cart");
// Convert to an array
data = JSON.parse(data);
// Traversing an array Find the data in the array that meets the conditions
var obj = data.find(v=>v.username==username && v.goodsid==$(this).parent().attr("data-id"));
obj.number = num;
localStorage.setItem("cart",JSON.stringify(data))
priceAndNumberAll()
})
$(".reduce").click(function(){
// Get first input The value in the box
var num = $(this).next().val()-0;
// Per click 1 Give way every time input The value inside ++
num --
// Data cannot be added wirelessly To make a judgment If added to the maximum value I won't let him add it
if(num<1){
num=1;
$(this).prop("disabled",true);
$(this).addClass("bgreduce");
$(this).next().next().prop("disabled",false)
}else{
$(this).prop("disabled",false);
$(this).next().next().removeClass("bgadd");
}
$(this).next().val(num)
var price = $(this).parent().prev().find("span").text()-0;
// Recalculate subtotal
var subtotal = price*num;
// After calculating the subtotal, put it in the storage one td Medium
$(this).parent().next().text(subtotal);
// Restoring data to local storage
var data = localStorage.getItem("cart");
data = JSON.parse(data);
// Find data that satisfies the addition
var obj = data.find(v=>{
return v.username==username&&v.goodsid==$(this).parent().attr("data-id");
})
obj.number = num;
localStorage.setItem("cart",JSON.stringify(data));
priceAndNumberAll()
})
}
10. Click the Delete button function
The code is as follows:
// Click the deleted function
function removebtn(){
// Click event
$(".btn").click(function(){
// Prompt whether to delete
if(!confirm(" Are you sure you want to delete it ")){
return false;
}
// Delete this data stored locally
var data = localStorage.getItem("cart");
data = JSON.parse(data);
var index = data.findIndex(function(v){
v.username==username&&v.goodsid==$(this).parent().siblings(".data-name").attr("data-id")
});
data.splice(index,1);
localStorage.setItem("cart",JSON.stringify(data))
var tr = $(this).parent().parent();
tr.remove()
if(!data.filter(v=>v.username==username).length){
// If the data is gone, the table will not be displayed
$(".page-middle").empty();
// Let the page display customized content
var str = "";
str += `<h2> The shopping cart is empty! ! ! </h2>
<p> Please quickly move to the list page and select the items <p><a href="./list.html" > Enter the list page </a>
`
$(".page-middle").html(str);
$(".page-middle").css({width:"1200px",margin:"40px auto 0"});
$(".page-middle h2").css({fontSize:"50px",lineHeight:"80px",color:"blue"})
}
})
}