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

发布于 2024-07-09 05:33:42 字数 354 浏览 11 评论 0原文

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

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

基本上是这样的的行:

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

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

Basically something along the lines of:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

蒗幽 2024-07-16 05:33:42

简单使用位置哈希

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

Simple use of location hash:

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}
离不开的别离 2024-07-16 05:33:42
  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
  }
  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
  }
被翻牌 2024-07-16 05:33:42

输入以下内容:

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

Put the following:

<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>
寄与心 2024-07-16 05:33:42

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

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

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

If the URI is not the document's location this snippet will do what you want.

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

if (hash) {
    alert(hash)
} else {
    // do something else
}
清醇 2024-07-16 05:33:42

你试过这个吗?

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

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

Have you tried this?

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

(Where url is the URL you want to check, obviously.)

差↓一点笑了 2024-07-16 05:33:42
$('#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!
});

这将解决问题;)

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

This will solve the problem ;)

睫毛上残留的泪 2024-07-16 05:33:42
window.location.hash 

将返回哈希标识符

window.location.hash 

will return the hash identifier

素年丶 2024-07-16 05:33:42

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

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

...or there's a jquery selector:

$('a[href^="#"]')
仅此而已 2024-07-16 05:33:42

您可以使用 现代 JS 解析 url:

var my_url = new URL('http://www.google.sk/foo?boo=123#baz');

my_url.hash; // outputs "#baz"
my_url.pathname; // outputs "/moo"
​my_url.protocol; // "http:"
​my_url.search; // outputs "?doo=123"

不带任何内容的 url哈希将返回空字符串。

You can parse urls using modern JS:

var my_url = new URL('http://www.google.sk/foo?boo=123#baz');

my_url.hash; // outputs "#baz"
my_url.pathname; // outputs "/moo"
​my_url.protocol; // "http:"
​my_url.search; // outputs "?doo=123"

urls with no hash will return empty string.

调妓 2024-07-16 05:33:42

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

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

Here's what you can do to periodically check for a change of hash, and then call a function to process the hash value.

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);
}
情未る 2024-07-16 05:33:42

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

Most people are aware of the URL properties in document.location. That's great if you're only interested in the current page. But the question was about being able to parse anchors on a page not the page itself.

What most people seem to miss is that those same URL properties are also available to anchor elements:

// 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
   }
});
一个人的夜不怕黑 2024-07-16 05:33:42
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; 
  }
}
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; 
  }
}
不醒的梦 2024-07-16 05:33:42
var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);
var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);
绝情姑娘 2024-07-16 05:33:42

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

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

Partridge and Gareths comments above are great. They deserve a separate answer.
Apparently, hash and search properties are available on any html Link object:

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

Or

<a href="bar.html?foo" onclick="alert(this.search)">SAY FOO</a>

Should you need this on a regular string variable and happen to have jQuery around,
this should work:

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

if ($('<a href="'+mylink+'">').get(0).search=='bar')) {
    // do stuff
}

(but its maybe a bit overdone .. )

娇柔作态 2024-07-16 05:33:42

将其作为从任意类似 URI 的字符串中抽象位置属性的方法放在这里。 尽管 window.location instanceof Location 为 true,但任何调用 Location 的尝试都会告诉您它是非法构造函数。 您仍然可以通过将字符串设置为 href 属性来获取诸如 hashqueryprotocol 等内容一个 DOM 锚元素,它将与 window.location 共享所有地址属性。

最简单的方法是:

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

string.hash;

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

Throwing this in here as a method for abstracting location properties from arbitrary URI-like strings. Although window.location instanceof Location is true, any attempt to invoke Location will tell you that it's an illegal constructor. You can still get to things like hash, query, protocol etc by setting your string as the href property of a DOM anchor element, which will then share all the address properties with window.location.

Simplest way of doing this is:

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

string.hash;

For convenience, I wrote a little library that utilises this to replace the native Location constructor with one that will take strings and produce window.location-like objects: Location.js

摇划花蜜的午后 2024-07-16 05:33:42

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

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

或者您可以使用以下方式监听位置:

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

我编写了一个 jQuery 插件 来执行某些操作喜欢
你想做什么。

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

Usually clicks go first than location changes,
so after a click is a good idea to setTimeOut
to get updated window.location.hash

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

or you can listen location with:

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

I wrote a jQuery plugin that does something like
what you want to do.

It's a simple anchor router.

场罚期间 2024-07-16 05:33:42

下面是一个返回 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 的评论。

Here is a simple function that returns true or false (has / doesn't have a hashtag):

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
}

Returns true in this case.

Based on @jon-skeet's comment.

温暖的光 2024-07-16 05:33:42

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

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

This is a simple way to test this for the current page URL:

  function checkHash(){
      return (location.hash ? true : false);
  }
等风也等你 2024-07-16 05:33:42

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

 const hasHash = string => string.includes('#')

您还可以像这样从 url 中删除哈希:

const removeHash = string => {
 const [url] = string.split('#')
 return url
}

最后您可以将逻辑组合在一起:

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

I noticed that all of these answers mostly check window.location.hash and make it difficult to write tests.

 const hasHash = string => string.includes('#')

You can also remove the hash from a url like so:

const removeHash = string => {
 const [url] = string.split('#')
 return url
}

And finally you can combine the logic together:

if(hasHash(url)) {
 url = removeHash(url)
}
凶凌 2024-07-16 05:33:42

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

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

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

returns -> #anchorlink

sometimes you get the full query string such as "#anchorlink?firstname=mark"

this is my script to get the hash value:

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

returns -> #anchorlink
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文