Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 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 Answer

0 votes
by (71.8m points)

Simple:(简单:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...