js 购物车数量增减,总价格联动变化

前端JS实现购物车功能,点击商品加减按钮商品数量加减,点击单选按钮和全选按钮颜色变化,总价联动变化。项目中应用的都是bootstrap的样式,css就不一一贴出来了。

加函数,减函数,手动修改数量判断库存函数,总价格计算函数,单选事件,全选事件,一共分为6个事件


<div class="orderwrap">
	<div class="ordertouch clearfix">
		<div class="ordercont">
			<div class="orderitem clearfix" priceOne>
				<div class="col-xs-1 clearPadding"></div>
				<div class="col-xs-3 clearPadding">
					<a href="">
						<img src="" alt="" class="img-responsive">
					</a>
				</div>
				<div class="col-xs-7 clearPadding pl10">
					<div class="proname"><a href="">原味手剥大瓜子</a></div>
					<div class="prodetail">
						<span class="font14 color-orange">¥<strong class="unitprice" unitprice>9.9</strong></span>
						<span class="pro_oriprice"><del>19.9</del></span>  
						<span class="color82 font12">库存:100</span>
					</div>
					<div class="pronum">
						<div class="pull-left input-group">
							<div class="num">数量:</div>
							<div class="btn-add omin" οnclick="minus(this,'9.9','100');" style="padding:2px 8px;">
								<span class="glyphicon glyphicon-minus"></span>
							</div>
							<input type="text" class="btn-num onum" value="" name='count' οnblur='amount_input(this,"9.9","100")' >
							<div class="btn-add oplus" οnclick="plus(this,'9.9}','100}');" style="padding:2px 8px;">
								<span class="glyphicon glyphicon-plus"></span>
							</div>
						</div>		
					</div>			
				</div>
				<div class="col-xs-1 clearPadding"></div>
				<i class="iconfont o-label op-label checkitem" productid='}'></i>
				<a href=""><div class="o-more"></div></a>
			</div>
		</div>
		<div class="btn-del" οnclick="btndel('',this)">删 除</div>
	</div>	
</div>
<div class="bottoms checkoutbox">
	<div class="col-xs-8  bordertop borderbottom">
		<div class="pull-left">
			<i class="o-label checkall iconfont" id="checkall"></i>
			<span class="qxposition">全选</span>
		</div>
		<div class="pull-right">
			<div class="">合计: ¥ <span class="font14 color-orange allprice" id="allprice">0</span></div>
			<div class="font12">不含运费</div>					
		</div>
	</div>
	<div class="col-xs-4 clearPadding"><button class="btn-checkout" οnclick="sbm();">结算(<span class="allnum" id="amount">0</span>)</button></div>
</div>


//计算总价
function setTotal(){
	var allprice=0;//总价格
	var allnum=0;//总数量
	$(".checkitem").each(function(){
		if($(this).hasClass('oncheck')){
			var num=parseInt($(this).parents('[priceOne]').find('input[name=count]').val());//单个商品的购买数量
			var price=$(this).parents('[priceOne]').find('[unitprice]').text();//商品单价需要从后台获取
			allprice+=num*price;//每样商品的总价
			allnum+=num;
		}		
	})
	$(".allprice").html(allprice.toFixed(2));
	$(".allnum").html(allnum);
}
setTotal();
//手动修改文本框商品数量与库存的限制
function amount_input(tag,sellprice,stock){
	var amount=parseInt($(tag).val());
	if(isNaN(amount)){
		layer.msg('最少购买量为1');
		$(tag).val(1);
	}else{
		if(amount>stock){
			layer.msg('购买数量不能大于库存');
			$(tag).val(stock);
		}else if(amount<1){
			layer.msg('最少购买量为1');
			$(tag).val(1);
		}
	}
	var val=parseFloat(sellprice)*parseInt($(tag).val());
	setTotal();
}
// 全选
$('#checkall').click(function(){
	$(this).toggleClass('oncheck');
	if($(this).hasClass('oncheck')){
		$('.checkitem').addClass('oncheck');
		setTotal();
	}else{
		$('.checkitem').removeClass('oncheck');
		setTotal();
	}
});
//单选
$('.checkitem').click(function(){
	$(this).toggleClass('oncheck');
	var itemsleng=$('.checkitem').length;
	var checkedleng=$('[priceOne]').find('i').filter('.oncheck').length;
	if(checkedleng==itemsleng){
		$('.checkall').addClass('oncheck');
		setTotal();
	}else{
		$('.checkall').removeClass('oncheck');
		setTotal();
	}
});
// 购买数量加
function plus(tag,sellprice,stock){
	var _this=$(tag);
	var input=_this.prev('input');
	if(_this.prev('input[disabled]').length>0){
		return;
	}
	var amount=parseInt(input.val());
	amount++;
	if(amount>stock){
		return layer.msg('购买数量不能大于库存');
	}else{
		input.val(amount);
		setTotal();
	}
}
// 购买数量减
function minus(tag,sellprice,stock){
	var _this=$(tag);
	var input=_this.next('input');
	if(_this.next('input[disabled]').length>0){
		return;
	}
	var amount=parseInt(input.val());
	amount--;
	if(amount<=0){
		return layer.msg('购买数量不能小于1');
	}else{
		input.val(amount);
		setTotal();
	}
}


  • 9
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
实现购物车功能可以分为以下几个步骤: 1. 创建一个商品类,包含商品的名称、价格、图片等信息。 ``` public class Product { private String name; private double price; private int image; public Product(String name, double price, int image) { this.name = name; this.price = price; this.image = image; } public String getName() { return name; } public double getPrice() { return price; } public int getImage() { return image; } } ``` 2. 创建一个购物车类,包含商品列表和总价格。 ``` public class ShoppingCart { private List<Product> productList; private double totalPrice; public ShoppingCart() { productList = new ArrayList<>(); totalPrice = 0; } public List<Product> getProductList() { return productList; } public void setProductList(List<Product> productList) { this.productList = productList; } public double getTotalPrice() { return totalPrice; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } public void addProduct(Product product) { productList.add(product); totalPrice += product.getPrice(); } public void removeProduct(Product product) { productList.remove(product); totalPrice -= product.getPrice(); } } ``` 3. 在界面中展示商品列表,并添加增减和删除按钮。 ``` public class MainActivity extends AppCompatActivity { private ListView listView; private TextView totalPriceTextView; private ShoppingCart shoppingCart; private ProductAdapter productAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = findViewById(R.id.list_view); totalPriceTextView = findViewById(R.id.total_price_text_view); shoppingCart = new ShoppingCart(); productAdapter = new ProductAdapter(this, shoppingCart.getProductList()); listView.setAdapter(productAdapter); Button addButton = findViewById(R.id.add_button); addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Product product = new Product("商品", 10.0, R.drawable.product); shoppingCart.addProduct(product); productAdapter.notifyDataSetChanged(); totalPriceTextView.setText("总价:" + shoppingCart.getTotalPrice()); } }); Button removeButton = findViewById(R.id.remove_button); removeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!shoppingCart.getProductList().isEmpty()) { Product product = shoppingCart.getProductList().get(0); shoppingCart.removeProduct(product); productAdapter.notifyDataSetChanged(); totalPriceTextView.setText("总价:" + shoppingCart.getTotalPrice()); } } }); } } ``` 4. 创建一个商品适配器类,用于展示商品列表。在适配器中实现商品数量增减商品的删除功能。 ``` public class ProductAdapter extends BaseAdapter { private Context context; private List<Product> productList; public ProductAdapter(Context context, List<Product> productList) { this.context = context; this.productList = productList; } @Override public int getCount() { return productList.size(); } @Override public Object getItem(int position) { return productList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.product_item, parent, false); } ImageView imageView = convertView.findViewById(R.id.image_view); TextView nameTextView = convertView.findViewById(R.id.name_text_view); TextView priceTextView = convertView.findViewById(R.id.price_text_view); ImageButton addButton = convertView.findViewById(R.id.add_button); final TextView countTextView = convertView.findViewById(R.id.count_text_view); ImageButton removeButton = convertView.findViewById(R.id.remove_button); final Product product = productList.get(position); imageView.setImageResource(product.getImage()); nameTextView.setText(product.getName()); priceTextView.setText("价格:" + product.getPrice()); countTextView.setText("数量:1"); addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int count = Integer.parseInt(countTextView.getText().toString()) + 1; countTextView.setText("数量:" + count); shoppingCart.setTotalPrice(shoppingCart.getTotalPrice() + product.getPrice()); notifyDataSetChanged(); totalPriceTextView.setText("总价:" + shoppingCart.getTotalPrice()); } }); removeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int count = Integer.parseInt(countTextView.getText().toString()) - 1; if (count < 1) { shoppingCart.removeProduct(product); productList.remove(product); } else { countTextView.setText("数量:" + count); shoppingCart.setTotalPrice(shoppingCart.getTotalPrice() - product.getPrice()); } notifyDataSetChanged(); totalPriceTextView.setText("总价:" + shoppingCart.getTotalPrice()); } }); return convertView; } } ``` 以上就是一个简单的购物车功能实现的示例。需要注意的是,实际项目中可能还需要处理一些其他的逻辑,例如商品库存不足时的提示等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值