以下是我的视线方法,希望对您有用,望采纳
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css" media="screen">
body{
background-color: #666;
}
.box{
width: 300px;
height: 400px;
background-color: fff
}
.shopInfoBox{
width: 100%;
height: 150px;
background-color: yellow;
}
.items{
list-style: none;
height: 60px;
}
.items .shopCrips{
width: 80%;
height: 100%;
float: left;
}
.items .shopCrips p{
margin: 0;
}
.items .addClick{
width: 20%;
float: left;
position: relative;
}
.items .addClick .spanBox{
width: 30px;
height: 30px;
text-align: center;
line-height: 30px;
font-size: 17px;
margin-top: 20px;
background-color: #000;
color: #fff;
cursor: pointer;
user-select: none;
}
.items .addClick span{
color: red;
font-size: 15px;
position: absolute;
top: 6px;
right: 17px;
}
</style>
</head>
<body>
<div class="box">
<div class="shopInfoBox">
<li class="items">
<div class="shopCrips">
<p>商品1</p>
<p>¥<span class="onlinePrice">30</span></p>
</div>
<div class="addClick">
<div class="spanBox">
+
</div>
<span class="numbers"></span>
</div>
</li>
<li class="items">
<div class="shopCrips">
<p>商品2</p>
<p>¥<span class="onlinePrice">50</span></p>
</div>
<div class="addClick">
<div class="spanBox">
+
</div>
<span class="numbers"></span>
</div>
</li>
</div>
<div class="shopca">
购物车
<span id="shopNum">0</span>
<span style="float: right;">¥<span id="price">0</span></span>
</div>
</div>
</body>
<script type="text/javascript" charset="utf-8" async defer>
window.onload = function(){
// 默认购物车价格,定义一个空数组
var allPrice = []
// 定义一个数组相加的方法
function sum(arr) {
return eval(arr.join("+"));
};
// 默认购物车数量
var shopNum = 0
// 获取所有商品的加号
var allShopAdd = document.getElementsByClassName('spanBox')
// 获取所有添加的数量
var allNumOfShop = document.getElementsByClassName('numbers')
// 获取搜索商品的单价
var onlinePrice =document.getElementsByClassName('onlinePrice')
// 获取购物车数量元素
var shopNumEle = document.getElementById('shopNum')
// 获取购物车价格元素
var allPriceEle = document.getElementById('price')
// 循环点击+号
for(let i=0;i<allShopAdd.length;i++){
// +号点击事件
let insItem = Number(allNumOfShop[i].innerHTML)
let onlinePrices = Number(onlinePrice[i].innerHTML)
allShopAdd[i].onclick = function(){
// 让购物车数量再每次点击都+1
shopNum+=1
shopNumEle.innerHTML = shopNum
// 让+号上面上个数字加1
insItem+=1
allNumOfShop[i].innerHTML = insItem
// 让购物车每个商品的总价添加到数组
allPrice[i] = onlinePrices*insItem
// 赋值
allPriceEle.innerHTML = sum(allPrice)
}
}
}
</script>
</html>