触发历史管理的三种方法:
- 跳转页面
- 改变hash值
- pushState(在服务器环境下运行)
用hash值来触发历史管理:
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <title>随机产生彩票号码</title> 5 <meta charset="utf-8"/> 6 <script> 7 window.onload = function(){ 8 var oInput = document.getElementById(‘input1‘); 9 var oDiv = document.getElementById(‘div1‘); 10 var json = {}; 11 12 oInput.onclick = function(){ 13 var result = randomNum(35,7); 14 var num = Math.random(); 15 json[num] = result; 16 oDiv.innerHTML = result; 17 window.location.hash = num; 18 } 19 20 window.onhashchange = function(){ 21 if(!this.location.hash.length){ 22 oDiv.innerHTML = ‘‘; 23 return; 24 } 25 oDiv.innerHTML = json[this.location.hash.substring(1)]; 26 } 27 28 } 29 30 function randomNum(allNum,selNum){ 31 var arr = []; 32 var newArr = []; 33 for(var i=0;i<allNum;i++){ 34 arr.push(i+1); 35 } 36 for(var j=0;j<selNum;j++){ 37 newArr.push(arr.splice(Math.floor(Math.random()*arr.length),1)); 38 } 39 return newArr; 40 } 41 42 43 </script> 44 45 46 </head> 47 48 <body> 49 <input type="button" id="input1" value="随机选号"/> 50 <div id="div1"></div> 51 52 53 </body> 54 55 56 57 </html>用pushState来触发历史管理:
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <title>随机产生彩票号码</title> 5 <meta charset="utf-8"/> 6 <script> 7 window.onload = function(){ 8 var oInput = document.getElementById(‘input1‘); 9 var oDiv = document.getElementById(‘div1‘); 10 oInput.onclick = function(){ 11 var result = randomNum(35,7); 12 oDiv.innerHTML = result; 13 14 history.pushState(result,‘‘,Math.random()); //三个参数,第一个参数是保存的值,第二个参数是title(并无用),第三个参数用来设置url 15 16 } 17 18 window.onpopstate = function(ev){ 19 oDiv.innerHTML = ev.state; 20 } 21 22 } 23 24 function randomNum(allNum,selNum){ 25 var arr = []; 26 var newArr = []; 27 for(var i=0;i<allNum;i++){ 28 arr.push(i+1); 29 } 30 for(var j=0;j<selNum;j++){ 31 newArr.push(arr.splice(Math.floor(Math.random()*arr.length),1)); 32 } 33 return newArr; 34 } 35 36 37 </script> 38 39 40 </head> 41 42 <body> 43 <input type="button" id="input1" value="随机选号"/> 44 <div id="div1"></div> 45 46 47 </body> 48 49 50 51 </html>
时间: 2024-12-23 23:10:24