如:A,B页面,A为商品页,B为购物车页,两个页面同时打开,在A页面点击商品添加至购物车,切换到B页面购物车怎么显示该商品信息
- 利用localStroage,A页面将数据存入localStroage,B页面读取localStorage中的数据
- 关键点: B页面如何知道A页面什么时候存数据到localStorage
- localStorage中有个‘storage’事件
- window.addEventListener(‘storage’, callback),A页面存数据,B页面监听事
A页面 <button id="add">添加一件商品到购物车</button> <button id="del">删除一件商品从购物车</button> <script type="text/javascript"> window.onload = function () { document.getElementById('add').onclick = function () { count(true) } document.getElementById('del').onclick = function () { count(false) } function count(flag) { let count = localStorage.getItem('count')?JSON.parse(localStorage.getItem('count')).count:0; if(flag){ count += 1; }else { if(!count) return; count -= 1; } let countObj = { count } localStorage.setItem('count', JSON.stringify(countObj)) } } B页面 <div class="cart"> 购物车产品数量: <span class="count">0</span> </div> <script type="text/javascript"> document.querySelector('.count').textContent = localStorage.getItem('count')?JSON.parse(localStorage.getItem('count')).count:0; window.addEventListener('storage', function (event) { console.log(JSON.parse(event.newValue).count); document.querySelector('.count').textContent = JSON.parse(event.newValue).count }) </script>