Programming

URL에서 조각 식별자 (해시 번호 다음의 값)는 어떻게 얻습니까?

procodes 2020. 5. 10. 11:50
반응형

URL에서 조각 식별자 (해시 번호 다음의 값)는 어떻게 얻습니까?


예:

www.site.com/index.php#hello

jQuery를 사용 hello하여 변수에 값을 넣고 싶습니다 .

var type = …

jQuery가 필요 없음

var type = window.location.hash.substr(1);

다음 코드를 사용하여 수행 할 수 있습니다.

var url = "www.site.com/index.php#hello";
var hash = url.substring(url.indexOf('#')+1);
alert(hash);

데모보기


var url ='www.site.com/index.php#hello';
var type = url.split('#');
var hash = '';
if(type.length > 1)
  hash = type[1];
alert(hash);

jsfiddle 작업 데모


URL에서 해시 (#) 후 값을 가져 오려면 다음 JavaScript를 사용하십시오. 이를 위해 jQuery를 사용할 필요가 없습니다.

var hash = location.hash.substr(1);

이 코드와 튜토리얼을 여기 에서 얻었습니다-JavaScript를 사용하여 URL에서 해시 값을 얻는 방법


런타임에서 URL을 얻었으므로 아래에서 정답을 제공했습니다.

let url = "www.site.com/index.php#hello";
alert(url.split('#')[1]);

도움이 되었기를 바랍니다


그건 매우 쉬워요. 아래 코드를 사용해보십시오

$(document).ready(function(){  
  var hashValue = location.hash;  
  hashValue = hashValue.replace(/^#/, '');  
  //do something with the value here  
});

AK의 코드를 기반으로 도우미 함수가 있습니다. 여기 JS 피들 ( http://jsfiddle.net/M5vsL/1/ ) ...

// Helper Method Defined Here.
(function (helper, $) {
    // This is now a utility function to "Get the Document Hash"
    helper.getDocumentHash = function (urlString) {
        var hashValue = "";

        if (urlString.indexOf('#') != -1) {
            hashValue = urlString.substring(parseInt(urlString.indexOf('#')) + 1);
        }
        return hashValue;
    };
})(this.helper = this.helper || {}, jQuery);

참고 URL : https://stackoverflow.com/questions/11662693/how-do-i-get-the-fragment-identifier-value-after-hash-from-a-url

반응형