localStorage实现购物车数量单价和结算页面的实时同步

While there is life there is hope.
一息若存,希望不灭

用localStorage实现简易的购物车数量单价和结算页面两个页面的实时同步:

购物车页面:
实时更新页面,在input的value发生改变的时候存储localStorage

<script>
window.onload=function(){
var oNum=document.getElementById('num');

oNum.onchange=function(){
localStorage.apple=oNum.value;
};
};
</script>
</head>
<body>
苹果:<input type="number" id="num" max="10" min="0" required step="2"/>
单价:20元/个
</body>

结算页面:
利用onstorage事件实时获取购物车页面实时存储的数据,并计算展示实时的总价格,当然我们可以继续完善这个页面

<script>
window.onload=function(){
var oDiv=document.getElementsByTagName('div')[0];

window.onstorage=function(ev){
oDiv.innerHTML='共消费¥'+localStorage.apple*20+'元';
};
};
</script>
</head>
<body>
<div>共消费¥元</div>
</body>

原文地址:https://www.cnblogs.com/jasonwang2y60/p/6018092.html