JavaScript development shopping cart tutorial for multiple product display
Display multiple products
The example introduced above is to display one product. When we copy the entire class="shop2" div , you will find the problem. No matter which + or - is clicked, the first product changes. This is because our trigger events are all targeted at the first product and have no universality. Therefore, we need to modify it. Our example
First pass all the variables used in the function as parameters
//Press + Button
function add(text,price,subtotal){
//Get the number of the current page
var num=document.getElementById(text).value;
//Add one to the quantity and then assign it to the value attribute in the
++num;
document.getElementById(text).value=num;
//Get the quantity of the current page, multiply it by the quantity, and assign it to the page display content of the div to which the subtotal belongs
## var price=document.getElementById(price).innerHTML;
var subtotal=price*num;
document.getElementById(subtotal).innerHTML=price*num;
}
//Press the - button
function minus(text,price,subtotal){
var num=document.getElementById(text).value;
//Determine whether the quantity is negative
if(--num<1){
## document.getElementById(text).value=0;}else{
document.getElementById(text).value=num
}
//Get the current page Quantity, multiplied by the quantity, assigned to the page display content of the div to which the subtotal belongs
//Reassigning num is to place the situation where num=-1 occurs
var num=document.getElementById(text).value;
## var price=document.getElementById(price).innerHTML;
document.getElementById(subtotal).innerHTML=price*num;
}
The other two functions are also Similarly:
//When the user changes the number in the box, the change() function is triggered after the cursor is out of focus
function change(text,price,subtotal){
//Determine whether the user input is a non-number, and if so, remind the user
if(isNaN(document.getElementById(text).value)){
## alert("Please enter a number");
document.getElementById(text).value=1;
}
//Get the value of the input box with id="text"
var num=document.getElementById(text).value;
//Get the product price
var price=document.getElementById(price).innerHTML;
//Output the subtotal
document.getElementById( subtotal).innerHTML=price*num;
}
##function delect(shop2){
//Delete the div with id="shop"
document.body.removeChild(document.getElementById(shop2));
}
After that Change all the IDs involved in the two products to be different. When the event is triggered, pass in different ID values
The complete code is as follows
简易购物车 简易购物车商品单价数量小计操作
Note: Our page still has many imperfections. For example, if you refresh it, the previously selected information will change to what it was during initialization. There is no memory of the user's choice, no function to select all, and no product pictures. Display, etc., we will improve these in the next version