Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

javascript - 如何使用JavaScript检查URL中的#哈希?(How can you check for a #hash in a URL using JavaScript?)

I have some jQuery/JavaScript code that I want to run only when there is a hash ( # ) anchor link in a URL.

(我有一些jQuery / JavaScript代码,仅在URL中有哈希( # )锚链接时才要运行。)

How can you check for this character using JavaScript?

(如何使用JavaScript检查此字符?)

I need a simple catch-all test that would detect URLs like these:

(我需要一个简单的包罗万象的测试,该测试可以检测如下URL:)

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

Basically something along the lines of:

(基本上是这样的:)

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

If anyone could point me in the right direction, that would be much appreciated.

(如果有人能指出我正确的方向,那将不胜感激。)

  ask by Philip Morton translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simple:

(简单:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...