JavaScriptを使用してURLの#hashを確認するにはどうすればよいですか?
-
08-07-2019 - |
質問
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);
}
ほとんどの人は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;
}
}
上記のパートリッジとガレスのコメントは素晴らしいです。彼らは別の答えに値します。 どうやら、ハッシュと検索のプロパティはすべてのhtml Linkオブジェクトで利用可能です:
<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
はtrueですが、 Location
を呼び出そうとすると、それが不正なコンストラクターであることがわかります。文字列を href
プロパティとして設定することで、 hash
、 query
、 protocol
などにアクセスできます。 DOMアンカー要素。すべてのアドレスプロパティを window.location
と共有します。
これを行う最も簡単な方法は次のとおりです。
var a = document.createElement('a');
a.href = string;
string.hash;
便宜上、これを利用して、ネイティブの Location
コンストラクターを文字列を取り、 window.location
のようなオブジェクトを生成するコンストラクターに置き換える小さなライブラリを作成しました。< a href = "https://gist.github.com/barneycarroll/5310151" rel = "nofollow"> Location.js
通常、場所の変更よりもクリックの方が先に進み、 したがって、クリック後はsetTimeOutをお勧めします 更新されたwindow.location.hashを取得するには
$(".nav").click(function(){
setTimeout(function(){
updatedHash = location.hash
},100);
});
または次の方法で場所を聞くことができます:
window.onhashchange = function(evt){
updatedHash = "#" + evt.newURL.split("#")[1]
};
次のようなことを行う 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);
}
&quot; #anchorlink?firstname = mark&quot;などの完全なクエリ文字列を取得する場合があります
これはハッシュ値を取得するための私のスクリプトです:
var hashId = window.location.hash;
hashId = hashId.match(/#[^?&\/]*/g);
returns -> #anchorlink