HTML5自学笔记[ 8 ]历史管理

触发历史管理的三种方法:

  1. 跳转页面
  2. 改变hash值
  3. pushState(在服务器环境下运行)

用hash值来触发历史管理:

 <!doctype html>
 <html lang="en">
 <head>
 <title>随机产生彩票号码</title>
 <meta charset="utf-8"/>
 <script>
 window.onload = function(){
     var oInput = document.getElementById('input1');
     var oDiv = document.getElementById('div1');
     var json = {};

     oInput.onclick = function(){
         var result = randomNum(35,7);
         var num = Math.random();
         json[num] = result;
         oDiv.innerHTML = result;
         window.location.hash = num;
     }

     window.onhashchange = function(){
         if(!this.location.hash.length){
             oDiv.innerHTML = '';
             return;
         }
         oDiv.innerHTML = json[this.location.hash.substring(1)];
     }

 }

 function randomNum(allNum,selNum){
     var arr = [];
     var newArr = [];
     for(var i=0;i<allNum;i++){
        arr.push(i+1);
     }
     for(var j=0;j<selNum;j++){
         newArr.push(arr.splice(Math.floor(Math.random()*arr.length),1));
     }
     return newArr;
 }

 </script>

 </head>

 <body>
 <input type="button" id="input1"  value="随机选号"/>
 <div id="div1"></div>

 </body>

 </html>

用pushState来触发历史管理:

 <!doctype html>
 <html lang="en">
 <head>
 <title>随机产生彩票号码</title>
 <meta charset="utf-8"/>
 <script>
 window.onload = function(){
     var oInput = document.getElementById('input1');
     var oDiv = document.getElementById('div1');
     oInput.onclick = function(){
         var result = randomNum(35,7);
         oDiv.innerHTML = result;

         history.pushState(result,'',Math.random());  //三个参数,第一个参数是保存的值,第二个参数是title(并无用),第三个参数用来设置url

     }

     window.onpopstate = function(ev){
         oDiv.innerHTML = ev.state;
     }

 }

 function randomNum(allNum,selNum){
     var arr = [];
     var newArr = [];
     for(var i=0;i<allNum;i++){
        arr.push(i+1);
     }
     for(var j=0;j<selNum;j++){
         newArr.push(arr.splice(Math.floor(Math.random()*arr.length),1));
     }
     return newArr;
 }

 </script>

 </head>

 <body>
 <input type="button" id="input1"  value="随机选号"/>
 <div id="div1"></div>

 </body>

 </html>
上一篇:[VS2008] 安装 AnkhSVN 后,选项中选择它,Pending Changes 窗口一闪而过,源代码管理工具自动跳回 【None】


下一篇:微信小程序-工具无法加载本地模拟开发服务的解决办法