小生愛

pushState、replaceState 无刷新例子

pushState replaceState例子

	          
	    /**
	      * 小生爱 - 2015.08.28

	      * window.history 对象

	      * 重点 : 1) 必须是同域下使用 不能跨域
	             2) 只能添加一级目录 如果是/a/b 不行
	      
	      * go(num) : 跳转第几页 num>0 向前跳转一页 num<0 向后跳转一页

	      * back() : 后退一页

	      * forward() : 前进一页

	      * history.state : 当前URL下对应的状态信息 如果当前URL不是通过pushState或者replaceState产生的 
	                那么history.state是null 等价于e.state

	      * pushState : 将当前URL和history.state加入到history中 并用新的state和URL替换当前
	            state : 与要跳转到的URL对应的状态信息 可以是任何形式的数据类型
	            title : 目前没有浏览器支持 可以留空
	            url : 要跳转的url地址 不能跨域

	      * onpopstate : 回退 前进 监听事件
	    */

	    
	    var i = 0;
	    

	    var addEvent = function (){
	      // 添加跳转
	      $('ul:eq(0) a').on('click', function (e){
	        e.preventDefault();
	        pushUrl($(this));
	      });


	      // go方法
	      $('ul:eq(1) a').on('click', function (e){
	        e.preventDefault();
	        goUrl($(this));
	      });


	      // back 
	      $('.back').on('click', function (e){
	        e.preventDefault();
	        history.back();
	      });


	      // forward
	      $('.forward').on('click', function (e){
	        e.preventDefault();
	        history.forward();
	      });


	      
	      $('.replace a').on('click', function (e){
	        e.preventDefault();
	        var href = $(this).attr('href');
	        var state = i++; console.log(state);
	        /**
	          * replaceState : 用新的state和URL替换当前的state和URL
	              state : 与要跳转到的URL对应的状态信息
	              title : 目前没有浏览器支持 可以留空
	              url : 要跳转的url地址 不能跨域
	        */ 
	        history.replaceState(state, '', href);
	      });
	    };
	    addEvent();


	    // pushState跳转 
	    var pushUrl = function (t){
	      var href = t.attr('href');
	      var state = i++; console.log(state, 'a');
	      /**
	        * pushState : 将当前URL和history.state加入到history中 并用新的state和URL替换当前
	            state : 与要跳转到的URL对应的状态信息
	            title : 目前没有浏览器支持 可以留空
	            url : 要跳转的url地址 不能跨域
	      */
	      history.pushState(state, '', href);
	    };


	    // go跳转到第几页
	    var goUrl = function (t){
	      // 第几页
	      var rel = t.attr('data-page');
	      // 跳转
	      history.go(rel);
	    };


	    // onpopstate : 回退 前进触发该事件
	    // 回退到上个页面以后 才触发
	    window.onpopstate = function (e){
	      // 输出pushState replaceState保存的state值
	      console.log(history.state, 'b');
	    };