历史管理-onhashchange&window.history

来源:互联网 发布:mysql商品表设计 编辑:程序博客网 时间:2024/05/19 02:40

网页记录历史记录两种方法


1.onhashchange事件  改变hash值来管理


   hash值:http://test.con#hash #后面内容即为hash值

    设置网页的hash值  window.location.hash = "要设置的hash值"

    获取hash值:var hash = window.location.hash.substring(1);//去掉#号

    直接修改网址的hash值,不刷新页面,是不会显示hash指定的模块,此时需要用到onhashchange事件 修改hash值后 按enter键即可正常显示

   window.onhashchange = function(){

window.location.reload()
   }

2.window.history事件

   通过两个方法 pushState存历史记录 

       window.history.pushState(“数据”,“标题”,“地址”);
window.history.pushState(“url”,“标题”,“#home”);
     地址即显示在网址后方的字符串
       标题没有浏览器支持

       历史记录前进后退时 使用popstate事件  通过e.state获取存入的数据
if (window.addEventListener) {window.addEventListener('popstate', function (e) {if (history.state && e.state) {var state = e.state;//操作代码}}, false);}




  
  





  
 


0 0
原创粉丝点击