2012-07-17 9 views
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> 

깊은 노트 : 내가 읽고 다음 질문에 내가 무엇을 찾고 찾을 COUT : How to detect URL change in JavaScript + How to change the current URL in javascript?

답변

6

, 당신은 '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); 
    }); 
}); 

주의 : 대체와Not all browsers support the hashchange event.

사용 : 당신이해야 use Modernizr to detect if hashchangeEvent is supported 및 지원 체크가 실패하면 Ben Alman's jQuery hashchange event plugin으로 대체하고 else 블록에서 @Baylor Rae의 솔루션을 사용하십시오.

+2

은 barlasapaydin이 지원하고자하는 브라우저 (http://caniuse.com/hashchange)에 따라 달라집니다. – voigtan

+0

완전히 업데이트 된 답변보기 – BumbleB2na

3

당신은 찾을 수 있습니다 Ben Alman의 jQuery hashchange event plugin가 도움이됩니다. jQuery를 이외의 다른 플러그인을 사용하지 않고

$(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(); 

}); 
관련 문제