[javascript] JavaScript를 사용하여 URL에서 #hash를 어떻게 확인할 수 있습니까?

#URL에 해시 ( ) 앵커 링크 가있는 경우에만 실행하려는 jQuery / JavaScript 코드가 있습니다. JavaScript를 사용하여이 문자를 어떻게 확인할 수 있습니까? 다음과 같은 URL을 감지하는 간단한 포괄 테스트가 필요합니다.

  • example.com/page.html#anchor
  • example.com/page.html#anotheranchor

기본적으로 다음과 같은 내용이 있습니다.

if (thereIsAHashInTheUrl) {        
    do this;
} else {
    do this;
}

누구든지 올바른 방향으로 나를 가리킬 수 있다면 대단히 감사하겠습니다.



답변

단순한:

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}


답변

  if(window.location.hash) {
      var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
      alert (hash);
      // hash found
  } else {
      // No hash found
  }


답변

다음을 넣으십시오.

<script type="text/javascript">
    if (location.href.indexOf("#") != -1) {
        // Your code in here accessing the string like this
        // location.href.substr(location.href.indexOf("#"))
    }
</script>


답변

URI가 문서의 위치가 아닌 경우이 스 니펫은 원하는 작업을 수행합니다.

var url = 'example.com/page.html#anchor',
    hash = url.split('#')[1];

if (hash) {
    alert(hash)
} else {
    // do something else
}


답변

이것을 시도 했습니까?

if (url.indexOf('#') !== -1) {
    // Url contains a #
}

( url확인하려는 URL은 어디에 있습니까 ?)


답변

$('#myanchor').click(function(){
    window.location.hash = "myanchor"; //set hash
    return false; //disables browser anchor jump behavior
});
$(window).bind('hashchange', function () { //detect hash change
    var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
    //do sth here, hell yeah!
});

이것은 문제를 해결할 것입니다;)


답변

window.location.hash 

해시 식별자를 반환합니다