할 수 있는 방법을 확인하#hash URL 에서 JavaScript 를 사용하여?
-
08-07-2019 - |
문제
나는 몇 가지 jQuery/JavaScript 코드는 실행하고 싶을 때만이 있는 해시(#
)앵커 링크에 URL 이 있습니다.당신은 어떻게 확인할 수 있습니다 이를 위해 캐릭터를 사용하여 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);
}
대부분의 사람들은 Document.Location의 URL 속성을 알고 있습니다. 현재 페이지에만 관심이 있다면 좋습니다. 그러나 문제는 페이지 자체가 아닌 페이지에서 앵커를 구문 분석 할 수 있다는 것이 었습니다.
대부분의 사람들이 놓치는 것처럼 보이는 것은 동일한 URL 속성이 요소를 고정시키는 데 사용할 수 있다는 것입니다.
// 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와 Gareths의 의견은 위대합니다. 그들은 별도의 대답을받을 자격이 있습니다. 분명히 HTML 링크 개체에서 해시 및 검색 속성을 사용할 수 있습니다.
<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>
또는
<a href="bar.html?foo" onclick="alert(this.search)">SAY FOO</a>
일반 문자열 변수에서 이것을 필요로하고 jQuery가있는 경우 작동해야합니다.
var mylink = "foo.html?bar#quz";
if ($('<a href="'+mylink+'">').get(0).search=='bar')) {
// do stuff
}
(하지만 아마도 약간 과도하게 ..)
var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);
던지기에서이기 위한 방법으로 추상화하는 위치에서 속성을 임의의 URI 같은 문자열입니다.지 window.location instanceof Location
사실,모든 시도를 invoke Location
는 당신을 말할 것이다 그것이 불법이 생성자입니다.당신은 여전히 얻을 수 있습 같은 것들 hash
, query
, protocol
등을 설정하여 귀하의 문자열로 href
의 속성 DOM 앵커 요소는 다음을 공유하는 모든 주소 속성 window.location
.
가장 간단한 방법:
var a = document.createElement('a');
a.href = string;
string.hash;
의 편의를 위해 내가 쓴 작은 라이브러리의 활용 이를 대체 원 Location
생성자 중 하나는 것이 문자열을 생산하고 window.location
같은 개체: Location.js
일반적으로 클릭이 위치가 변경되는 것보다 먼저 진행되므로 클릭 한 후에는 Window.Location.hash를 업데이트하기 위해 시간을 설정하는 것이 좋습니다.
$(".nav").click(function(){
setTimeout(function(){
updatedHash = location.hash
},100);
});
또는 위치를들을 수 있습니다.
window.onhashchange = function(evt){
updatedHash = "#" + evt.newURL.split("#")[1]
};
나는 a jQuery 플러그인 그것은 당신이하고 싶은 것과 같은 일을합니다.
간단한 앵커 라우터입니다.
다음은 반환하는 간단한 기능입니다 true
또는 false
(해시 태그가 없음) :
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
}
보고 true
이 경우.
@jon-skeet의 의견을 기반으로합니다.
이것은 현재 페이지 URL에 대해 이것을 테스트하는 간단한 방법입니다.
function checkHash(){
return (location.hash ? true : false);
}
때때로 "#anchorlink? firstName = mark"와 같은 전체 쿼리 문자열이 나타납니다.
해시 값을 얻는 내 스크립트입니다.
var hashId = window.location.hash;
hashId = hashId.match(/#[^?&\/]*/g);
returns -> #anchorlink