边看视频边做的练习,随机显示数字,分别使用history和hash来实现历史管理
<!doctype html> <html> <head> <meta charset="utf-8" > <title>随机显示数字</title> <style type="text/css"> *{ padding: 0; margin: 0; } #btn1,#div1{ margin: 10px; } </style> </head> <body> <input type="button" value="请随机选择" id="btn1" /> <div id="div1"></div> <script type="text/javascript"> // history,需在服务器下运行 window.onload = function(){ var oBtn1 = document.getElementById('btn1'); var oDiv1 = document.getElementById('div1'); oBtn1.onclick = function(){ var arr = randomNum(35,7); history.pushState(arr,'',arr); // 三个参数,数据、标题(没有效果)、地址(可选) oDiv.innnerHTML = arr; } window.onpopstate = function(ev){ oDiv.innnerHTML = ev.state; // popstate事件,读取数据 event.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; } } //onhashchange通过改变hash值来管理 window.onload = function(){ var oBtn1 = document.getElementById('btn1'); var oDiv1 = document.getElementById('div1'); //var json = {}; oBtn1.onclick = function(){ var arr = randomNum(35,7); var num = Math.random(); json[num] = arr; oDiv1.innerHTML = arr; window.location.hash = num; } window.onhashchange = function(){ oDiv1.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> </html>