<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>点击添加或减少数量,总价随之改变(keyup的用法)</title>
<link rel="stylesheet" href="style.css">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport" />
<style>
/*增添人数*/
html{font-size:100px;}
.font20{font-size:0.2rem;}
.numhuman {width:4.1rem;margin:0 auto;overflow:hidden;}
.numhuman img{width:0.91rem;float:left;}
.shownum{width:1.7rem;height:0.71rem;background:#ffb900;float:left;margin:0 0.06rem;}
.shownum span,#goods_num{text-align:center;color:#333;font-size:0.4rem;display:block;height:0.71rem;line-height:0.71rem}
</style>
</head>
<body>
<br>
<div class="numhuman">
<img id="reducebtn" src="images/reduce.png" >
<div class="shownum">
<input id="goods_num" style="width:70%;float:left;" type="text" value="1">
<span style="width:28%;float:right;font-size:0.32rem;">人</span>
</div>
<img id="addbtn" src="images/add.png" >
</div>
<span class="font20">单价:</span><span id="single_price" style="color:#333;font-size:0.28rem;">10</span><span class="font20">元</span>
<span class="font20">总价:</span><span id="total_price" style="color:#333;font-size:0.28rem;"></span><span class="font20">元</span>
<script src="jquery.min.js"></script>
<script>
var goods_num=$(‘#goods_num‘).val();
console.log(goods_num);
var single_price=$(‘#single_price‘).html();
$(‘#total_price‘).html(goods_num*single_price);
// 添加购买人数开始
// 单价
var single_price = $(‘#single_price‘).html();
// 减人数 按钮
$(‘#reducebtn‘).click(function(){
var goods_num = $(‘#goods_num‘).val();
if(goods_num <= 0){
goods_num = 0;
}else{
goods_num--
}
$(‘#goods_num‘).val(goods_num);
$(‘#total_price‘).html(goods_num*single_price);
})
// 添加人数按钮
$(‘#addbtn‘).click(function(){
var goods_num = $(‘#goods_num‘).val();
goods_num++;
$(‘#goods_num‘).val(goods_num);
$(‘#total_price‘).html(goods_num*single_price)
})
$(‘#goods_num‘).keyup(function(){
var goods_num = $(‘#goods_num‘).val().replace(/[^\d]+/,‘‘);
$(‘#goods_num‘).val(goods_num);
$(‘#total_price‘).html(goods_num*single_price)
})
</script>
</body>
</html>