your programing

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

lovepro 2020. 9. 29. 08:21
반응형

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당연히 확인하려는 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 

해시 식별자를 반환합니다.


... 또는 jquery 선택기가 있습니다.

$('a[href^="#"]')

해시 변경을 주기적으로 확인한 다음 해시 값을 처리하는 함수를 호출하기 위해 수행 할 수있는 작업은 다음과 같습니다.

var hash = false; 
checkHash();

function checkHash(){ 
    if(window.location.hash != hash) { 
        hash = window.location.hash; 
        processHash(hash); 
    } t=setTimeout("checkHash()",400); 
}

function processHash(hash){
    alert(hash);
}

Most people are aware of the URL properties in document.location. That's great if you're only interested in the current page. But the question was about being able to parse anchors on a page not the page itself.

What most people seem to miss is that those same URL properties are also available to anchor elements:

// To process anchors on click    
jQuery('a').click(function () {
   if (this.hash) {
      // Clicked anchor has a hash
   } else {
      // Clicked anchor does not have a hash
   }
});

// To process anchors without waiting for an event
jQuery('a').each(function () {
   if (this.hash) {
      // Current anchor has a hash
   } else {
      // Current anchor does not have a hash
   }
});

function getHash() {
  if (window.location.hash) {
    var hash = window.location.hash.substring(1);

    if (hash.length === 0) { 
      return false;
    } else { 
      return hash; 
    }
  } else { 
    return false; 
  }
}

Partridge and Gareths comments above are great. They deserve a separate answer. Apparently, hash and search properties are available on any html Link object:

<a id="test" href="foo.html?bar#quz">test</a>
<script type="text/javascript">
   alert(document.getElementById('test').search); //bar
   alert(document.getElementById('test').hash); //quz
</script>

Or

<a href="bar.html?foo" onclick="alert(this.search)">SAY FOO</a>

Should you need this on a regular string variable and happen to have jQuery around, this should work:

var mylink = "foo.html?bar#quz";

if ($('<a href="'+mylink+'">').get(0).search=='bar')) {
    // do stuff
}

(but its maybe a bit overdone .. )


var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);

Throwing this in here as a method for abstracting location properties from arbitrary URI-like strings. Although window.location instanceof Location is true, any attempt to invoke Location will tell you that it's an illegal constructor. You can still get to things like hash, query, protocol etc by setting your string as the href property of a DOM anchor element, which will then share all the address properties with window.location.

Simplest way of doing this is:

var a = document.createElement('a');
a.href = string;

string.hash;

For convenience, I wrote a little library that utilises this to replace the native Location constructor with one that will take strings and produce window.location-like objects: Location.js


Usually clicks go first than location changes, so after a click is a good idea to setTimeOut to get updated window.location.hash

$(".nav").click(function(){
    setTimeout(function(){
        updatedHash = location.hash
    },100);
});

or you can listen location with:

window.onhashchange = function(evt){
   updatedHash = "#" + evt.newURL.split("#")[1]
};

I wrote a jQuery plugin that does something like what you want to do.

It's a simple anchor router.


Here is a simple function that returns true or false (has / doesn't have a hashtag):

var urlToCheck = 'http://www.domain.com/#hashtag';

function hasHashtag(url) {
    return (url.indexOf("#") != -1) ? true : false;
}

// Condition
if(hasHashtag(urlToCheck)) {
    // Do something if has
}
else {
    // Do something if doesn't
}

Returns true in this case.

Based on @jon-skeet's comment.


This is a simple way to test this for the current page URL:

  function checkHash(){
      return (location.hash ? true : false);
  }

sometimes you get the full query string such as "#anchorlink?firstname=mark"

this is my script to get the hash value:

var hashId = window.location.hash;
hashId = hashId.match(/#[^?&\/]*/g);

returns -> #anchorlink

참고URL : https://stackoverflow.com/questions/298503/how-can-you-check-for-a-hash-in-a-url-using-javascript

반응형