现在有许多网站支持SPI(single page interface),和传统的MPI(multi page interface)比起来,它无需载入新的网页,速度会快很多,用户体验也会好很多。唯一的问题是如果你的页面改动很大,比如切换tab,页面大部分内容由ajax载入。用户会以为跳转到另一个页面,这时如果他们点击后退按钮,SPI就会出问题了,因为我们只有一个页面。
解决办法就是使用hashchange事件。一方面是当你切换tab时,在url里加入hash,javascript里是location.hash;另一方面是当hash变化是捕捉到该事件,大部分新的浏览器支持onhashchange事件。
至于IE6,7,我们需要用iframe去模拟这两个方面。
这里推荐一个jquery plugin: http://benalman.com/projects/jquery-hashchange-plugin/
我的一个例子:
//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.
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.
来源:oschina
链接:https://my.oschina.net/u/104775/blog/94260