hashchange 插件


(function($){

var hashchange = 'hashchange', DOC = document, documentMode = DOC.documentMode,
supportHashChange = ('on' + hashchange in window) && ( documentMode === undefined || documentMode > 7 );

$.fn[ hashchange ] = function(callback){
return callback? this.bind(hashchange, callback ) : this.trigger( hashchange);
};
$.fn[ hashchange ].delay = 50;
if(!supportHashChange){
//$.log("不支持hashchange,使用iframe加定时器模拟")
var iframe, timeoutID, html = '<!doctype html><html><body>{0}</body></html>';

if( $.fn[ hashchange ].domain){
html = html.replace("<body>","<script>document.domain ="+
$.fn[ hashchange ].domain +"</script><body>" )
}

function format(html,hash){
return html.replace('{0}', hash);
}
function getHash ( url) {//用于取得当前窗口或iframe窗口的hash值
url = url || DOC.URL;
return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' );
}
function getHistory(){
return getHash(iframe.location);
}
function setHistory(hash, history_hash){
var doc = iframe.document;
if ( hash !== history_hash ) {//只有当新hash不等于iframe中的hash才重写
//用于产生历史
doc.open();
doc.write(format(html, hash));
doc.close();
}
}
var last_hash = getHash(), history_hash, hash = "";

$.event.special[ hashchange ] = {
setup: function() {
$(function(){
if (!iframe) {
var el = $('<iframe tabindex="-1" style="display:none" width="0" height="0" />').appendTo( document.body );
el.one("load",function(){
iframe = this.contentWindow;
var doc = iframe.document;
doc.open();
doc.write(format(html, last_hash));
doc.close();
timeoutID = setInterval(poll, $.fn[ hashchange ].delay);
});

function poll() {
var hash = getHash(),//取得主窗口中的hash
history_hash = iframe.document.body.innerText;//取得现在iframe中的hash
if(hash !== last_hash){//如果是主窗口的hash发生变化
setHistory(last_hash = hash, history_hash );
$(window).trigger(hashchange,[hash] );
}else if(history_hash !== last_hash){//如果按下回退键,
location.href = location.href.replace( /#.*/, '' ) + history_hash;
}
}
}
});

},
teardown: function(){
if(!iframe){
clearTimeout(timeoutID);
$(iframe).remove();
iframe = null;
}
}
};
}
})(jQuery);




<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="../jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="hashchange.js"></script>

</head>
<body>
<a href="#a?id=10">aaaa</a>
<a href="#b?id=11&bb=11">bbbb</a>
<a href="#c?id=12&cc=11">cccc</a>
<div id="log" width="300px;" height="200px" style="border:1px solid #ccc;"></div>
<script>
$(function(){
$(window).hashchange(function(e,hash){
$('#log').append('<div>' + document.location + '【<strong>'+hash+ '</strong>】</div>');
});
$(window).hashchange();
});
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值