html5 history 信息api pushState

这个功能可以进行传参,还可以解决ajax无法前进和倒退的问题

 

 

首先,history新增的两个方法history.replaceState()和history.pushState()方法属于HTML5浏览器新增的属性,所以IE9以下的是不支持的。

 

直接上代码:

history.replaceState() 顾名思义就是替换的意思,所以它的作用就是替换当前地址栏的url

 

[html] view plain copy
 
  1. <!DOCTYPE HTML>  
  2. <head>  
  3.   <script src="jquery-1.8.2.min.js"></script>  
  4.       
  5. <style>  
  6.   
  7. </style>  
  8. <script>  
  9. $(function(){  
  10.     $("#bt").click(function(){  
  11.         history.replaceState({data:111},"1222","aa.html");  
  12.         return false;  
  13.     });  
  14. })  
  15.   
  16. </script>  
  17. </head>  
  18. <body class="sapUiBody">  
  19.     <input type="button" id="bt" value="show">  
  20.       
  21. </body>  

点击按钮后,可以看到页面地址栏的地址变了,但是页面并没有刷新。

 

history.replaceState(data,"页面的title","需要改变的url") 接收三个参数

 

history.pushState() 看到push大家首先应该想到的是数组,没错,这个方法就是往浏览器的history里压入一条url,就像数据结构里的栈一样,这个压入的url会在栈

的最顶端,当你点击浏览器的前进或者倒退按钮时,便会拿出栈顶的url来定位,从而达到改变history的作用但是并不刷新!

 

 

[html] view plain copy
 
  1. <!DOCTYPE HTML>  
  2. <head>  
  3.   <script src="jquery-1.8.2.min.js"></script>  
  4.       
  5. <style>  
  6.   
  7. </style>  
  8. <script>  
  9. $(function(){  
  10.     $("#bt").click(function(){  
  11.         history.pushState({data:111},"1222","aa.html");  
  12.         history.pushState({data:111},"1222","ab.html");//多压入几条  
  13.         return false;  
  14.     });  
  15. })  
  16.   
  17. </script>  
  18. </head>  
  19. <body class="sapUiBody">  
  20.     <input type="button" id="bt" value="show">  
  21.       
  22. </body>  


其次是

window.addEventListener('popstate', function(event) {     
   console.log(event.state);//data 
});

还记得上面的pushState方法么,当你往history的栈里通过调用这个方法压入多条数据时,并且你通过点击浏览器的前进倒退按钮进行改变的时候,这个事件就触发了,然后就

是event.state就是上面方法的第一个参数data,并且是和url一一对应的,这样就实现了传值

 

 

 

[html] view plain copy
 
  1. <!DOCTYPE HTML>  
  2. <head>  
  3.   <script src="jquery-1.8.2.min.js"></script>  
  4.       
  5. <style>  
  6.   
  7. </style>  
  8. <script>  
  9. $(function(){  
  10.     $("#bt").click(function(){  
  11.         history.pushState({data:111},"1222","aa.html");  
  12.         history.pushState({data:111},"1222","ab.html");//多压入几条  
  13.         return false;  
  14.     });  
  15.       
  16.     window.addEventListener('popstate', function(event) {       
  17.         console.log(event.state);    
  18.         });  
  19. })  
  20.   
  21. </script>  
  22. </head>  
  23. <body class="sapUiBody">  
  24.     <input type="button" id="bt" value="show">  
  25.       
  26. </body>  


最后,通过这种方法可以在popstate的事件里写自己的逻辑了,如发送ajax等

posted @ 2018-03-18 19:13  上帝不是要你成功,而是让你去尝试  阅读(169)  评论(0编辑  收藏  举报