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

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

基本上是这样的:

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

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

有帮助吗?

解决方案

简单的:

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

其他提示

  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
  }

输入以下内容:

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

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

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

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

你试过这个吗?

if (url.indexOf("#") != -1)
{
}

(在哪里 url 显然,这是您要检查的 URL。)

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

这将解决问题;)

window.location.hash 

将返回哈希标识符

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

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

您可以执行以下操作来定期检查哈希值的更改,然后调用函数来处理哈希值。

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

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

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

(但可能有点过头了..)

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

将其作为从任意类似 URI 的字符串中抽象位置属性的方法放在这里。虽然 window.location instanceof Location 是真的,任何调用的尝试 Location 会告诉你这是一个非法的构造函数。你仍然可以做类似的事情 hash, query, protocol 等通过将你的字符串设置为 href DOM 锚元素的属性,然后该元素将与以下对象共享所有地址属性 window.location.

最简单的方法是:

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

string.hash;

为了方便起见,我编写了一个小库,利用它来替换本机 Location 构造函数,其中一个将接受字符串并生成 window.location类物体: 位置.js

通常点击先去而不是位置更改, 所以点击后设置TimeOut是个好主意 获取更新的 window.location.hash

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

或者您可以通过以下方式收听位置:

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

我写了一个 jQuery 插件 这有点像 您要执行的操作。

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

这是一个返回的简单函数 true 或者 false (有/没有主题标签):

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

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

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

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

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

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

returns -> #anchorlink
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top