项目分享第二章
详情页面实现方法,因为没有后端接口使用,所以我使用的是localstorage来传递商品信息
$('.content-c').on('click','li',function(){
let obj = {img:$(this).children('img').attr('src'),price:$(this).children('h4').text(),title:$(this).children('p').text()}
localStorage.setItem('xq',JSON.stringify(obj))
window.location.href = '../../pages/xq.html'
})
给所有的商品加点击事件,然后在商品被点击的时候用该商品的信息创建一个对象,因为我们的local storage中只能存字符串,所以要先将这个对象转化为json数据格式,然后存到同一个local storage中,点击不同的商品时,local storage中的数据会被替换,
详情页面中商品添加购物车的方法实现,
var arr = []
if (localStorage.getItem('cart')) {
arr = JSON.parse(localStorage.getItem('cart'))
}else{
localStorage.setItem('cart',JSON.stringify(arr))
}
$('button').click(function () {
if (JSON.parse(localStorage.getItem('cart')).some(v => v.title == obj.title)) {
alert('商品已添加,请去购物车选择数量')
} else {
arr.push(obj)
localStorage.setItem('cart',JSON.stringify(arr))
}
})
首先我们先定义一个空数组,因为我们的local storage只能存一个字符串,我们要想存多条有关联的数据,就需要存一个数组,先定义一个空数组,然后把每次需要添加的数据push进去,在把这个数组转化为json格式存到local storage中,
如果我们的local storage中之前有数据,我们不能每次都向新数组里面push内容,这样会删掉之前的数据,所以我们做一个判断,先获取到local storage中’cart’这个值,如果有内容就把这个数据转化为我们JS格式赋值给arr 如果没有他获取到的就是空,我们向空arr中push内容就好了,