本文针对未登录时对购物车的本地存储进行批量删除操作来阐述的,单个删除比较简单,这里就不做介绍了,下面开始正文。
首先,先取出localStorage中存取的购物车列表
var list = JSON.parse(localStorage.getItem('unlogin_cart_list'))
其次,判断用户是否勾选底部全选,如果勾选就直接把整个列表从localStorage删除
if($('.cart_checked_all').attr('src') == './images/goods/checked.png'){ //这里我是根据勾选和未勾选的图片路径来判断是否全选
localStorage.removeItem('unlogin_cart_list')
$('.manage_text_right').hide() //隐藏右上角管理按钮
$('.bbctouch-cart-bottom').hide() //隐藏底部结算栏
}
如果未勾选全选则根据选中的商品id进行删除
1、遍历所有商品,找出选中的商品
var checkedArr = [] //选中商品id数组
var select_num = 0 //选中商品数量
$('.goods_checked_one').each(function(key,item){
if($(item).attr('src') == './images/goods/checked.png'){
select_num++
checkedArr.push($(item).parent().parent().data('gid'))
}
})
if(select_num == 0){ //如果未勾选给个提示
layer.open({
content:'请选择删除的商品',
shade:true
time: 2,
})
}else{
...这里是有勾选的情况,如下2
}
2、遍历本地存储的购物车列表,找到与勾选匹配的商品并删除(这里可根据自己的数据结构进行遍历)
list.forEach(function(item,index1){
checkedArr.forEach(function(item3){
item[2].forEach(function(item2,index2){
if(item2.gid == item3){
delete list[index1][2][index2]
}
})
})
})

注意!!! 使用delete删除时会出现empty,要使用filter进行过滤

3、去除数组中的空值
var newArr = []
list.forEach(function(item,index1){
newArr[index1] = item
newArr[index1][2] = item[2].filter(function(item1,index2){
return item1
})
})
4、过滤之后有的店铺只有一件商品并且被删除,此时会出现空数组,再继续过滤掉长度为0的数组
var tempArr = newArr.filter(function(v,i){
return v[2].length != 0
})
5、最后,把过滤得到删除后的购物车列表存入localStorage中
localStorage.setItem('unlogin_cart_list',JSON.stringify(tempArr))
完整代码如下(顺序略有调整):
$('.delete_cart_goods').click(function(){
var checkedArr = []
var select_num = 0
//对所有店铺内商品进行遍历
$('.goods_checked_one').each(function(key,item){
if($(item).attr('src') == './images/goods/checked.png'){
select_num++
checkedArr.push($(item).parent().parent().data('gid'))
}
})
if(select_num == 0){
layer.open({
content:'请选择删除的商品',
shade:true
time: 2,
})
}else{
var list = JSON.parse(localStorage.getItem('unlogin_cart_list'))
if(list.length>0){
//如果全选删除都直接删除localStorage中整个购物车
if($('.cart_checked_all').attr('src') == './images/goods/checked.png'){
localStorage.removeItem('unlogin_cart_list')
$('.manage_text_right').hide()
$('.bbctouch-cart-bottom').hide()
}else{
//删除勾选的商品
list.forEach(function(item,index1){
checkedArr.forEach(function(item3){
item[2].forEach(function(item2,index2){
if(item2.gid == item3){
delete list[index1][2][index2]
}
})
})
})
console.log(list)
// 去除数组中的空值
var newArr = []
list.forEach(function(item,index1){
newArr[index1] = item
newArr[index1][2] = item[2].filter(function(item1,index2){
return item1
})
})
// 过滤长度为0的数组
var tempArr = newArr.filter(function(v,i){
return v[2].length != 0
})
localStorage.setItem('unlogin_cart_list',JSON.stringify(tempArr))
}
}
}
})
附上一张效果图
以上只是我个人对购物车批量删除的理解,肯定还有更好的方法,欢迎大家讨论交流,感谢感谢,笔芯。