如何使用JavaScript检查URL中的#哈希?

我有一些jQuery / JavaScript代码,仅在URL中有哈希( # )锚链接时才要运行。 如何使用JavaScript检查此字符? 我需要一个简单的包罗万象的测试,该测试可以检测如下URL:

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

基本上是这样的:

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

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


#1楼

...或者有一个jQuery选择器:

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

#2楼

通常,点击优先于位置更改,因此单击之后,最好设置setTimeOut以获得更新的window.location.hash

$(".nav").click(function(){
    setTimeout(function(){
        updatedHash = location.hash
    },100);
});

或者您可以使用以下方法收听位置:

window.onhashchange = function(evt){
   updatedHash = "#" + evt.newURL.split("#")[1]
};

我编写了一个jQuery插件 ,该插件的功能类似于您想要执行的操作。

这是一个简单的锚路由器。


#3楼

window.location.hash 

将返回哈希标识符


#4楼

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

#5楼

var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);

#6楼

大多数人都知道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
   }
});

#7楼

将其作为从任意类似URI的字符串中提取位置属性的方法而放在这里。 尽管window.location instanceof Location是正确的,但任何尝试调用Location都将告诉您这是一个非法的构造函数。 通过将字符串设置为DOM锚元素的href属性,您仍然可以进行hashqueryprotocol等操作,然后将其与window.location共享所有地址属性。

最简单的方法是:

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

string.hash;

为方便起见,我编写了一个小库,利用该库将本地Location构造函数替换为一个将接收字符串并产生window.location的对象的构造函数: Location.js


#8楼

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

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

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

returns -> #anchorlink

#9楼

简单:

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

#10楼

你有尝试过吗?

if (url.indexOf('#') !== -1) {
    // Url contains a #
}

(显然,其中url是您要检查的URL。)


#11楼

输入以下内容:

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

#12楼

您可以按照以下步骤定期检查哈希值的变化,然后调用一个函数来处理哈希值。

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

#13楼

这是一个简单的函数,返回truefalse (有/没有#标签):

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的评论。


#14楼

这是测试当前页面URL的简单方法:

  function checkHash(){
      return (location.hash ? true : false);
  }

#15楼

  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
  }

#16楼

$('#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!
});

这将解决问题;)


#17楼

上面的Partridge和Gareths评论很棒。 他们应该得到一个单独的答案。 显然,哈希和搜索属性在任何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
}

(但可能有点过头了。)


#18楼

如果URI不在文档的位置,则此片段将执行您想要的操作。

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

if (hash) {
    alert(hash)
} else {
    // do something else
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值