HTML5——同步购物车

 

同步购物车,及打开两个或多个界面,选择购物时同步,让显示的内容一致,这样不至于购买出错。

核心:利用storage事件和localStorage本地存储实现

图片简单展示:

 

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
    <title>同步购物车</title>
<script type="text/javascript">
window.onload=function(){
    var aInput=document.getElementsByTagName('input');
    for(var i=0;i<aInput.length;i++){
        aInput[i].onclick=function(){
            if(this.checked){
    window.localStorage.setItem('sel',this.value);
            }else{
    window.localStorage.setItem('onSel',this.value);
            }
        };
    }
    //addEventListener是JS绑定事件写法
    window.addEventListener('storage',function(ev){ //当前页面的事件不会触发此事件(storage)
     if(ev.key=='sel'){
         for(var i=0;i<aInput.length;i++){
             if(ev.newValue==aInput[i].value){                 
                 aInput[i].checked=true;
             }
         }
     }else if(ev.key=='onSel'){     
         for(var i=0;i<aInput.length;i++){
             if(ev.newValue==aInput[i].value){
                 aInput[i].checked=false;
             }
         }     
     }
    });
}

</script>
</head>
<body>
<input type="checkbox" value="香蕉"/>香蕉<br/>
<input type="checkbox" value="苹果"/>苹果<br/>
<input type="checkbox" value="橘子"/>橘子<br/>
<input type="checkbox" value=""/>糖<br/>
<input type="checkbox" value="西瓜"/>西瓜<br/>
<input type="checkbox" value="葡糖"/>葡糖<br/>
</body>
</html>

 

posted @ 2016-04-27 23:16  shuai7boy  阅读(781)  评论(0编辑  收藏  举报