1、onhashchange:改变hash值来进行历史管理。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <input type="button" value="随机选择" id="btn" /> 9 <div id="div1"></div> 10 </body> 11 </html> 12 <script> 13 window.onload = function(){ 14 var oBtn = document.getElementById("btn"); 15 var oDiv = document.getElementById("div1"); 16 window.json = {}; 17 oBtn.onclick = function(){ 18 var key = Math.random(); 19 var value = randomNum(35,7); 20 json[key] = value; 21 //oDiv.innerHTML = value; 22 window.location.hash = key; 23 } 24 25 window.onhashchange = function(){ 26 var hashValue = window.location.hash.substring(1); 27 if(!hashValue)return; 28 oDiv.innerHTML = json[hashValue]; 29 } 30 } 31 32 function randomNum(totlaNum,resultNum){ 33 var totalArray = new Array(); 34 var resultArray = new Array(); 35 for(var i = 0 ;i < totlaNum;i++){ 36 totalArray.push(i); 37 } 38 39 for(var i = 1; i<= resultNum;i++){ 40 resultArray.push(totalArray.splice(Math.floor(Math.random()*totalArray.length),1)); 41 } 42 return resultArray; 43 } 44 </script>
2、history+pushState+ popstate事件:需要在服务器下运行。网址是虚假的,需要服务器指定对应页面,否则刷新找不到页面。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <input type="button" value="随机选择" id="btn" /> 9 <div id="div1"></div> 10 </body> 11 </html> 12 <script type="text/javascript"> 13 window.onload = function(){ 14 var oBtn = document.getElementById("btn"); 15 var oDiv = document.getElementById("div1"); 16 window.json = {}; 17 oBtn.onclick = function(){ 18 var value = randomNum(35,7); 19 //pushState接收三个参数 :数据 标题(都没实现) 地址(可选) 20 window.history.pushState(value,""); 21 oDiv.innerHTML = value; 22 } 23 24 window.onpopstate = function(ev){ 25 oDiv.innerHTML = ev.state; 26 } 27 28 } 29 30 function randomNum(totlaNum,resultNum){ 31 var totalArray = new Array(); 32 var resultArray = new Array(); 33 for(var i = 0 ;i < totlaNum;i++){ 34 totalArray.push(i); 35 } 36 37 for(var i = 1; i<= resultNum;i++){ 38 resultArray.push(totalArray.splice(Math.floor(Math.random()*totalArray.length),1)); 39 } 40 return resultArray; 41 } 42 </script>
时间: 2024-11-03 22:46:25