3

「document.location.hash」でURLを削除し、現在のURLから何が残っているかを確認しようとしています。プラグインを使用したくないし、クリックなどのトリガー イベントから結果を学習したくありません。URL の変更を即時かつ現代的に学習する必要があります。

jQuery:

$(function() {
    $(document).location().change(function() {//this part is not working
        var anchor = document.location.hash;
        if( anchor === '#one' ) {
            alert('current url = #one');
        }else if ( anchor === '#two' ) {
            alert('current url = #two');
        }else if ( anchor === '#three' ) {
            alert('current url = #three');
        }
        console.log(anchor);
    });
});

html:

<a href="#one">one</a>
<a href="#two">two</a>
<a href="#three">three</a>

深い注意: 私はこれらの質問を読み、私が探しているものを見つけました: JavaScript で URL の変更を検出する方法+ JavaScriptで現在の URL を変更する方法?

4

2 に答える 2

6

jQuery 以外のプラグインを使用しなくても、「hashchange」イベントを処理できます。

$(document).ready(function() {
    $(window).bind( 'hashchange', function(e) { 
    var anchor = document.location.hash;
            if( anchor === '#one' ) {
                alert('url = #one');
            }else if ( anchor === '#two' ) {
                alert('url = #two');
            }else if ( anchor === '#three' ) {
                alert('url = #three');
            }
            console.log(anchor);
    });
});

注意: すべてのブラウザーが hashchange イベントをサポートしているわけではありません。

フォールバックで使用する: Modernizrを使用して hashchangeEvent がサポートされているかどうかを検出し、そのサポート チェックが失敗した場合は、Ben Alman の jQuery hashchange イベント プラグインにフォールバックし、else ブロックで @Baylor Rae のソリューションを使用する必要があります。

于 2012-07-17T15:29:49.280 に答える
3

Ben Alman の jQuery hashchange イベント プラグインが役に立つかもしれません。

$(function(){

  // Bind the event.
  $(window).hashchange( function(){
    // Alerts every time the hash changes!
    alert( location.hash );
  });

  // Trigger the event (useful on page load).
  $(window).hashchange();

});
于 2012-07-17T15:21:54.057 に答える