JQuery 实现购物栏物品的添加与删除 总价计算案例

xiaoxiao2021-02-28  62

页面添加jQuery代码,实现以下功能: 1、 用户点击一个商品图片时,能够添加一个同样的商品图片到右侧购物车区块中。 2、 用户点击购物车中的商品图片时,能够移除这个商品 3、 在添加和移除商品的过程中,实时更新计费购物车中所有商品的总价,计费结果添加到购物车字样右侧的span区块中。

HTML代码: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>腾讯微信商城</title> <style type='text/css'> html,body {     height:100%; } #cart {     position:absolute;     right:0;     top:0;     width:270px;          background:#ccc; } img{     width: 270px;     height: 100px;     display:block; } </style> <script src='./jquery-1.8.3.min.js'></script> <script> </script> </head> <body>     限时促销:     <img src="./01.png" price='9.50' alt="">     <img src="./02.png" price='21.37' alt="">     <img src="./03.png" price='7.12' alt="">     <img src="./04.png" price='14.25' alt="">     <img src="./05.png" price='14.25' alt="">     <img src="./06.png" price='14.25' alt="">     <img src="./07.png" price='21.37' alt="">     <img src="./08.png" price='11.87' alt=""> <div id='cart'>     <span>购物车    </span>总计:¥<span id='total'>0</span>元 </div> </body> </html> JS代码: <script type="text/javascript"> 第一种方法 function count(){     var total=0;//不添加商品时 总价格为0     $('#cart img').each(function(){         //对 购物车的商品进行价格遍历统计并 计算总价格         total+=parseFloat($(this).attr('price'));     })     //对计算的总价进行计算 保留三位小数 并放入显示栏里     $('#total').html(total.toFixed(3)); } //页面加载完成显示商品及总价 $(function(){     //给商品图片绑定点击事件     $('img').on('click',function(){         //点击商品列表中的图片 复制一份到购物车内         var imgs=$(this).clone();         imgs.appendTo('#cart');         //添加商品后计算 商品栏总价         count();         //点击移除商品         //给 复制进购物栏的图片绑定单击事件         // 这一步非常重要 不能$('#cast img').on('click',function(){})这样绑定         // 会出现有几个商品 调用count()函数的现象         imgs.on('click',function(){             $(this).remove();             //移除商品后计算总价             count();         });     }); }); //第二种方法     var price = 0;     $('img').click(function(){         var obj = $(this).clone()         obj.prependTo($('#cart'));         price += parseFloat($(this).attr('price'));         // alert(price.toFixed(2));         $('#total').text(price.toFixed(2));         obj.click(function(){             $(this).remove();             price -= parseFloat($(this).attr('price'));             // alert(price.toFixed(2));             $('#total').text(price.toFixed(2));         })     }); </script>

转载请注明原文地址: https://www.6miu.com/read-58784.html

最新回复(0)