html5 历史管理onhashchange和state

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<script>
 window.onload=function(){
        var oin=document.getElementById('input1');
        var odiv=document.getElementById('div1');
        var json={};
        oin.onclick=function(){
            /*随机获取num值*/
            var num=Math.random();
             /*获取随机7位数*/
            var arr=randomNum(35,7);
           /* 随机索引存arr随机7位数*/
            json[num] =arr;
            odiv.innerHTML=arr;
            window.location.hash=num;
        }
        window.onhashchange=function(){
            odiv.innerHTML=json[window.location.hash.substring(1)];
        }

       function randomNum(iAll,iNow)
       {
            var arr=[];
            var newArr=[];
            for(var i=1; i<iAll; i++){
                arr.push(i);
                }
                for(var i=0; i<iNow; i++)
                {
                    newArr.push(arr.splice(Math.floor(Math.random()*arr.length),1));
                }
                return newArr;
       }
 }
</script>
<body>
    <input type="button" value="随机选择" id="input1">
    <div id="div1"></div>
</body>
</html>

随机数组的的索引存值

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<script>
 window.onload=function(){
        var oin=document.getElementById('input1');
        var odiv=document.getElementById('div1');
        oin.onclick=function(){
          var arr=randomNum(35,7);
          /*要存的数组*/
          history.pushState(arr,'');
          odiv.innerHTML=arr;
        };
        /*取数组的函数*/
        window.onpopstate=function(ev)
        {
          odiv.innerHTML=ev.state;
        }

       function randomNum(iAll,iNow)
       {
            var arr=[];
            var newArr=[];
            for(var i=1; i<iAll; i++){
                arr.push(i);
                }
                for(var i=0; i<iNow; i++)
                {
                    newArr.push(arr.splice(Math.floor(Math.random()*arr.length),1));
                }
                return newArr;
       }
 }
</script>
<body>
    <input type="button" value="随机选择" id="input1">
    <div id="div1"></div>
</body>
</html>

此方法只适合在服务器上使用

posted @ 2017-01-02 18:45  distant-遥远  阅读(406)  评论(0编辑  收藏  举报