购物车逻辑

当我们添加购物车之后,我们可以点击加减按钮来实现商品数量的增加和减少,当商品数量变化的同时商品的总的价格也是在不停的变化的。

效果图

购物车逻辑_第1张图片

完整代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title></title>
 <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
 
 </head>
 <body>
  <p>商品数量: <span onclick="numDec()">-</span> <input type="text" id="quantity" value="1" /> <span onclick="numAdd()">+</span></p>
   <p class="sdsd">商品价格: <span id="totalPrice">28.10</span></p>
   <input type="hidden" value="28.1" id="price" />
 </body>
 <script type="text/javascript">

 function keyup(){
     var quantity = document.getElementById("quantity").value;
     if(isNaN(quantity) ||  parseInt(quantity)!=quantity || parseInt(quantity)<1){
         quantity = 1;
         return;
     }
     if(quantity>=10){
         document.getElementById("quantity").value=quantity.substring(0,quantity.length-1);
         alert("商品数量不能大于10");
     }
 }  
 

 function numAdd(){
     var quantity = document.getElementById("quantity").value;
     var num_add = parseInt(quantity)+1;
     var price=document.getElementById("price").value;
     if(quantity==""){
         num_add = 1;
     }
     if(num_add>=10){
         document.getElementById("quantity").value=num_add-1;
         alert("商品数量不能大于10");
     }else{
         document.getElementById("quantity").value=num_add;
         var Num=price*num_add;
         document.getElementById("totalPrice").innerHTML=Num.toFixed(2);
     }
 }
 /*商品数量-1*/
 function numDec(){
     var quantity = document.getElementById("quantity").value;
     var price=document.getElementById("price").value;
     var num_dec = parseInt(quantity)-1;
     if(num_dec>0){
         document.getElementById("quantity").value=num_dec;
         var Num=price*num_dec;
          document.getElementById("totalPrice").innerHTML=Num.toFixed(2);
     }
 }

 </script>  
 </html>

购物车逻辑_第2张图片

你可能感兴趣的:(H5,JavaScript)