html5 history 信息api pushState

这个功能能够进行传参,还能够解决ajax没法前进和倒退的问题html

 

 

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

 

直接上代码:ajax

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

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

 

 

[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>  


其次是.net

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

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

是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等

相关文章
相关标签/搜索