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

IT技术 javascript jquery anchor fragment-identifier
2021-01-19 13:47:08

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

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

基本上是这样的:

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

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

6个回答

位置哈希的简单使用

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}
.search在 上可用<a>,不在 上.query示例 jQuery:$("<a/>").attr({ "href": "http://www.somewhere.com/a/b/c.html?qs=1#fragmenttest" })[0]. .hash => "#fragmenttest".search= ?qs=1从那里,点击查询字符串提取问题以获取字符串以外的内容。
2021-03-22 13:47:08
附加: .location 对象仅在当前窗口的 URL 上可用,您不能对任意 URL(例如存储在字符串变量中的 URL)执行此操作
2021-03-25 13:47:08
此外,像 .hash 和 .query 这样的位置属性也可用于 <a> 元素
2021-04-09 13:47:08
  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 contains a #
}

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