hashchange前端页面跳转

如今有许多网站支持SPI(single page interface),和传统的MPI(multi page interface)比起来,它无需载入新的网页,速度会快不少,用户体验也会好不少。惟一的问题是若是你的页面改动很大,好比切换tab,页面大部份内容由ajax载入。用户会觉得跳转到另外一个页面,这时若是他们点击后退按钮,SPI就会出问题了,由于咱们只有一个页面。 javascript


解决办法就是使用hashchange事件。一方面是当你切换tab时,在url里加入hash,javascript里是location.hash;另外一方面是当hash变化是捕捉到该事件,大部分新的浏览器支持onhashchange事件。 html

至于IE6,7,咱们须要用iframe去模拟这两个方面。 java


这里推荐一个jquery plugin: http://benalman.com/projects/jquery-hashchange-plugin/ jquery

个人一个例子: ajax

//include jquery plugin  
          var prefix = 'hash-';
         
          // Bind the event.
          $(window).hashchange( function(){
              
               var hash = window.location.hash.replace( /^[^#]*#?(.*)$/, '$1' );
              
               if((hash == (prefix+'tab4')) || ((hash == ''))){
                    if($('#blockdisplay4:visible').length == 0){
                         
                    }
               }else if((hash == (prefix+'tab1')) || ((hash == '') ) ){
                    if($('#blockdisplay1:visible').length == 0){
                                          
                    }
               }
          })
     
          // Trigger the event (useful on page load).
          $(window).hashchange();
         
          $('a[href]').live('click',function(){
               var hash = window.location.hash.replace( /^[^#]*#?(.*)$/, '$1' );
               var newhash = prefix + $(this).attr('href').replace( /^[^#]*#?(.*)$/, '$1' );
               if(hash != newhash){
                    window.location.hash = newhash;                   
               }

});
最后注意hash的名字不能是html中已有的id,否则ie会出问题:

http://stackoverflow.com/questions/1078501/keeping-history-of-hash-anchor-changes-in-javascript 浏览器

Surprise quirk bonus #1! In Internet Explorer 6, whenever there's a question mark in the hash, this gets extracted and put in the location.searchproperty! It is removed from the location.hash property. If there is a real query string, however, location.search will contain that one instead, and you'll only be able to get the whole true hash by parsing the location.href property. ide

Surprise quirk bonus #2! If the location.search property is set, any subsequent # characters will be removed from the location.href (and location.hash) property. In Internet Explorer 6 this means that whenever there's a question mark in the path or the hash, you'll experience this quirk. In Internet Explorer 7, this quirk only occurs when there's a question mark in the path. Don't you just love the consistency in Internet Explorer? 网站

Surprise quirk bonus #3! If another element on the page has the same id as the value of a hash, that hash will totally mess up the history. So rule of thumb is to avoid hashes with the same id as any elements on the page. If the hashes are generated dynamically and may collide with ids, consider using a prefix/suffix. ui

相关文章
相关标签/搜索