如何使用JavaScript检查URL中的散列?

如何使用JavaScript检查URL中的散列?,javascript,jquery,anchor,fragment-identifier,Javascript,Jquery,Anchor,Fragment Identifier,我有一些jQuery/JavaScript代码,我只想在URL中有散列(#)锚链接时运行这些代码。如何使用JavaScript检查此字符?我需要一个简单的全面测试,可以检测如下URL: example.com/page.html#anchor example.com/page.html#另一个主播 基本上是这样的: if (thereIsAHashInTheUrl) { do this; } else { do this; } 如果有人能给我指出正确的方向,

我有一些jQuery/JavaScript代码,我只想在URL中有散列(
#
)锚链接时运行这些代码。如何使用JavaScript检查此字符?我需要一个简单的全面测试,可以检测如下URL:

  • example.com/page.html#anchor
  • example.com/page.html#另一个主播
基本上是这样的:

if (thereIsAHashInTheUrl) {        
    do this;
} else {
    do this;
}
如果有人能给我指出正确的方向,我将不胜感激。

简单:

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}
你试过这个吗

if(url.indexOf('#')!=-1){
//Url包含一个#
}
(其中
url
显然是您要检查的url。)

放置以下内容:

<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>

if(location.href.indexOf(“#”)!=-1){
//这里的代码访问如下字符串
//location.href.substr(location.href.indexOf(“#”))
}

以下是定期检查哈希值变化的方法,然后调用函数处理哈希值

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);
}

这将解决问题;)

帕特里奇和加雷斯的上述评论非常好。他们应该得到一个单独的答案。 显然,哈希和搜索属性可用于任何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>

警报(document.getElementById('test').search)//酒吧
警报(document.getElementById('test').hash)//库兹


如果您需要对常规字符串变量使用此函数,并且碰巧有jQuery, 这应该起作用:

var mylink = "foo.html?bar#quz";

if ($('<a href="'+mylink+'">').get(0).search=='bar')) {
    // do stuff
}
var mylink=“foo.html?bar#quz”;
if($('').get(0.search=='bar')){
//做事
}

(但可能有点过头了。)

如果URI不是文档的位置,则此代码段将执行您想要的操作

var url = 'example.com/page.html#anchor',
    hash = url.split('#')[1];

if (hash) {
    alert(hash)
} else {
    // do something else
}

…或者有一个jquery选择器:

$('a[href^="#"]')

通常,单击比位置更改更重要, 因此,单击后设置超时是一个好主意 获取更新的window.location.hash

$(".nav").click(function(){
    setTimeout(function(){
        updatedHash = location.hash
    },100);
});
或者,您可以通过以下方式收听位置:

window.onhashchange = function(evt){
   updatedHash = "#" + evt.newURL.split("#")[1]
};
我写了一个类似 你想做什么

这是一个简单的锚路由器

window.location.hash 

将返回哈希标识符

大多数人都知道document.location中的URL属性。如果你只对当前页面感兴趣,那就太好了。但问题是能够解析页面上的锚,而不是页面本身

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; 
  }
}
大多数人似乎忽略的是,这些相同的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
   }
});

将其作为从任意URI(如字符串)中提取位置属性的方法。尽管location的
window.location instanceof location
为true,但任何调用
location
的尝试都会告诉您它是非法构造函数。通过将字符串设置为DOM锚元素的
href
属性,您仍然可以获得诸如
散列
查询
协议
等内容,然后该属性将与
窗口.位置
共享所有地址属性

最简单的方法是:

var a = document.createElement('a');
a.href = string;

string.hash;

为了方便起见,我编写了一个小库,利用它将本机的
Location
构造函数替换为一个将接受字符串并生成
window.Location
-类似对象的构造函数:

有时您会得到完整的查询字符串,例如“#anchorlink?firstname=mark”

这是我获取哈希值的脚本:

var hashId = window.location.hash;
hashId = hashId.match(/#[^?&\/]*/g);

returns -> #anchorlink

下面是一个简单的函数,它返回
true
false
(有/没有hashtag):

在这种情况下,返回
true


根据@jon skeet的评论。

这是一种针对当前页面URL测试此功能的简单方法:

  function checkHash(){
      return (location.hash ? true : false);
  }
您可以使用以下方法解析URL:

var my_url=新url('http://www.google.sk/foo?boo=123#baz');
my_url.hash;//输出“#baz”
我的url.pathname;//输出“/moo”
​my_url.protocol;//“http:”
​my_url.search;//输出“?doo=123”

没有散列的URL将返回空字符串。

我注意到所有这些答案都主要检查window.location.hash,这使得编写测试变得困难

 const hasHash = string => string.includes('#')
您还可以从url中删除哈希,如下所示:

const removeHash = string => {
 const [url] = string.split('#')
 return url
}
最后,您可以将逻辑组合在一起:

if(hasHash(url)) {
 url = removeHash(url)
}

附加:.location对象仅在当前窗口的URL上可用,您不能对任意URL(例如存储在字符串变量中的URL)执行此操作,诸如.hash和.query之类的位置属性在元素
上也可用。
上可以使用search
来获取字符串以外的内容。@hitsautodestruct:这个问题不是关于哈希值的更改,而是关于页面加载中是否存在哈希值。@Gareth是的,您是对的。刚刚意识到我发布的链接是针对
hashchange
事件的,而不是
window.location.hash
。虽然IE<8不支持后者,但这只是IE 6+7中的必要条件。所有其他浏览器都包含了onhashchangeevent@Tokimon-太好了!我不知道。但我想我们还是要支持那些旧版本的IEYeah。。。即使IE 8也不会在XP不支持IE 9的情况下很快消失:(在旧浏览器上实现hashchange事件(以及一系列其他现代功能)这根本不是推荐的代码:至少应该是:
setTimeout(checkHash,400)
。此外,现代浏览器有
hashchange
事件,因此您可以执行
窗口。addEventListener('hashchange',function(){…})
。最后,泄漏全局
hash
变量是另一种不推荐的做法,即使对于示例也是如此。这应该是“hash.length”而不是“hash.length()”?:)+1对于不知道什么是越界的Javascript:)@Dunc:Well JS数组基本上是对象。通过索引访问它们就像访问对象属性一样:
obj['0']
。在JS中,这是正确的:
arr[0]==arr['0']
因此,如果索引/键不存在,则返回值是未定义的,而不是超出范围。不可能,因为哈希附加在查询字符串之后,并且从不发送给ser
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
}
  function checkHash(){
      return (location.hash ? true : false);
  }
 const hasHash = string => string.includes('#')
const removeHash = string => {
 const [url] = string.split('#')
 return url
}
if(hasHash(url)) {
 url = removeHash(url)
}