let infoList = []
let totalMoney = 0
let projectList = [
{ name: 'a', price: 1 },
{ name: 'b', price: 2 },
{ name: 'c', price: 3 },
{ name: 'd', price: 4 },
] //获取到的商品列表,含有商品的价格等信息
// all 全选input $('.all),list:每一项$('.item') 下的input
getCheck($('.all'), $('.item input'))
function getCheck(all, list) {
all.click(function () {
infoList = []
if (this.checked) {
list.prop("checked", true);
//$.each() 循环jquery dom,下边真实数组还用foreach进行循环
$.each(list, function () {
console.log($(this))
infoList.push($(this).data('type'));
});
/**总价 */
totalMoney = 0
infoList.forEach((e, i) => {
console.log(e, i)
totalMoney += Number(projectList[i].price)
})
totalMoney = Number(totalMoney).toFixed(2)//显示的价格保留两位小数
$(".total").text(totalMoney);
} else {
list.prop("checked", false);
infoList = []
/**总价 */
totalMoney = 0.00
$(".total").text(totalMoney);
}
});
list.on('click', function () {
infoList = []
totalMoney = 0
let flag = true
$.each(list, function () {
if (this.checked) {
infoList.push($(this).data('type'));
}
});
for (let i = 0; i < list.length; i++) {
if (list[i].checked === false) {
flag = false
}
all[0].checked = flag
}
/**总价 */
totalMoney = 0
infoList.forEach(i => {
totalMoney += Number(projectList [i].price)
})
totalMoney = Number(totalMoney).toFixed(2)
$(".total").text(totalMoney);
})
return infoList
}
<div class="title">
<input type="checkbox" class="all">
<span>项目</span>
<span>价格</span>
</div>
<!-- 这里可以是动态插入的,data-type值为接口返回商品列表的下标,为了取出对应的价格-->
<ul class="list">
<li class="item">
<input type="checkbox" data-type="0">
<span>a</span>
<span>1</span>
</li>
<li class="item">
<input type="checkbox" data-type="1">
<span>b</span>
<span>2</span>
</li>
<li class="item">
<input type="checkbox" data-type="2">
<span>c</span>
<span>3</span>
</li>
<li class="item">
<input type="checkbox" data-type="3">
<span>d</span>
<span>4</span>
</li>
</ul>
<!--总计-->
<div class="total"></div>
知识点:
//定义和用法
jQuery.each() 函数用于遍历指定的对象和数组。
//语法
$.each( object, callback )
$.each() 可以循环dom,数组,forEach()只能循环数组
prop() 方法设置或返回被选元素的属性和值。
当该方法用于返回属性值时,则返回第一个匹配元素的值。
当该方法用于设置属性值时,则为匹配元素集合设置一个或多个属性/值对。
返回属性的值:
$(selector).prop(property)
设置属性和值:
$(selector).prop(property,value)