如何使用JavaScript检查URL中的#hash? [英] How can you check for a #hash in a URL using JavaScript?

查看:169
本文介绍了如何使用JavaScript检查URL中的#hash?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些jQuery JavaScript代码,只有在URL中有哈希(#)锚链接时才能运行。如何使用JavaScript检查此角色?我需要一个简单的全能测试来检测这些网址:

I have some jQuery JavaScript code that I want to run only when there is a hash (#) anchor link in a URL. How can you check for this character using JavaScript? I need a simple catch-all test that would detect URLs like these:


  • example.com/page.html#anchor

  • example.com/page.html#anotheranchor

基本上是这样的:

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

如果有人能指出我正确的方向,那将非常感激。

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

推荐答案

简单:

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

这篇关于如何使用JavaScript检查URL中的#hash?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆