Location.hashの値を監視し、変化があった場合、プログラムを呼び出す。おもにAjax向け
Ajaxで、ページを書き換えしていると、ページを指定したリンクが使えない。
そこで、読み込み時に、lovcation.hashを調べて、「#」以降の文字を調べて、ページにジャンプすればよい
しかし、まぁ〜書き出すと長くなるので監視するやつを書いてみた。
が、しかしである。
new しないと使えないのである。やっぱりごみだ。
あとでかきなおそっと!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> p { margin-bottom: 200px; } </style> <body> <p> <a href="#a">to a</a> <a href="#b">to b</a> <a href="#c">to c</a> </p> <p id="a">a</p> <p id="b">b</p> <p id="c">c</p> <script type="text/javascript"> var LocationHash = function ( ) { this.init.apply( this, arguments ); }; //初期化 LocationHash.prototype.init = (function ( ) { return function ( interval, cbFunc, cbObject ) { this.defInterval = 350; this.timerId = null; this.interval = interval; this.hash = location.hash; this.cbFunc = cbFunc; this.cbObject = cbObject; this.start(); }; })(); //チェック中断 LocationHash.prototype.stop = (function ( ) { return function ( ) { this.timerId && clearInterval( this.timerId ); return this.timerId = null; }; })(); //チェック開始 LocationHash.prototype.start = (function ( ) { return function ( ) { var checker = this.check; this.stop(); this.timerId = setInterval( (function( that ) { return function ( ) { that.check (); }; })( this ), this.interval ); }; })(); //Hashチェック LocationHash.prototype.check = (function ( ) { return function ( ) { var hash = location.hash; if( hash != this.hash ) { this.hash = hash; if( 'function' === typeof this.cbFunc ) return this.cbFunc.call( this.cbObject, hash ); } }; })(); new LocationHash( 1000, function (hash) { alert( hash ); } ); </script> </body> </html>