localStorage的跨頁面通信運用涵妥,以購物車為例
說到這里条摸,就不得不說一下onstorage事件了,當(dāng)存儲空間中數(shù)據(jù)發(fā)生變化的時候觸發(fā)該事件代芜,以下例子中有實際運用。
需要有兩個HTML文件浓利,第一個文件用來存數(shù)據(jù)挤庇,第二個文件用來取數(shù)據(jù),具體代碼如下:
物品界面.html
<script>
document.addEventListener('DOMContentLoaded',function(){
var oN = document.getElementById('num');
/*當(dāng)input的數(shù)據(jù)改變的時候*/
oN.onchange = function(){
/*存一個key為num的數(shù)據(jù)*/
localStorage.num = this.value;
};
},false);
</script>
<body>
物品:<input type="number" name="num" id="num" min="0" max="10" step="2" value="0">
</body>
結(jié)算界面.html
<script>
document.addEventListener('DOMContentLoaded',function(){
var oP = document.getElementById('price');
/*當(dāng)存儲空間中數(shù)據(jù)發(fā)生變化的時候*/
window.onstorage = function(ev){
/*獲取正在變化的數(shù)據(jù)*/
var n = localStorage[ev.key]*20;
oP.innerHTML = n;
};
},false);
</script>
<body>
物品總價:<strong id="price">0</strong>
</body>