jQuery 从 url 获取哈希值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13344221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:32:37  来源:igfitidea点击:

Get hash value from url

jqueryurlhash

提问by grindking

I'm trying to get the hash value after a link was clicked. Any ideas?

单击链接后,我试图获取哈希值。有任何想法吗?

e.g.

例如

The Link

链接

index.html#needThis

This is my result:

这是我的结果:

index.htmlneedThis

How can I remove the 'index.html' ?

如何删除“index.html”?

$('#myselector').on('click', 'a', function(){
    var hash = $(this).attr('href').replace('#', '') //get url
    console.log(hash);
})

回答by Gabriele Petrioli

update

更新

Modern browsers (not sure how back it goes) can extract the hashdirectly from anchor elements (so i added #5)

现代浏览器(不确定它是如何返回的)可以hash直接从锚元素中提取(所以我添加了 #5



Take your pick ..

随你挑..

  1. var hash = $(this).attr('href').split('#')[1];
  2. var hash = $(this).attr('href').replace(/^.*?#/,'');
  3. var href = $(this).attr('href'), hash = href.substr(href.indexOf('#')+1);
  4. var hash = $(this).attr('href').match(/#(.*$)/)[1];
  5. var hash = this.hash.substr(1);
  1. var hash = $(this).attr('href').split('#')[1];
  2. var hash = $(this).attr('href').replace(/^.*?#/,'');
  3. var href = $(this).attr('href'), hash = href.substr(href.indexOf('#')+1);
  4. var hash = $(this).attr('href').match(/#(.*$)/)[1];
  5. var hash = this.hash.substr(1);


update

更新

Just revisited this and i believe that #2 can be improved to

刚刚重新审视了这个,我相信 #2 可以改进为

$(this).attr('href').replace(/^.*?(#|$)/,'');

This way if no hash exists it will return empty instead of the whole url..

这样,如果不存在哈希,它将返回空而不是整个 url..

回答by Kirill Ivlev

Just use var hash = window.location.hash.

只需使用var hash = window.location.hash.

It returns everything after #

它返回 # 之后的所有内容

Or if you've got a variable which contains an url:

或者,如果您有一个包含 url 的变量:

$(this).attr('href').substring($(this).attr('href').indexOf('#'))

回答by Wasim Shaikh

You can try with window location hash.

您可以尝试使用窗口位置哈希。

$('#myselector').on('click', 'a', function(){
    var hash = $(this).attr('href').replace('#', '') //get url
    var hash2 = window.location.hash ;
    console.log(hash2);
})

回答by jucedogi

Why not simply use:

为什么不简单地使用:

window.location.hash

Works just fine for me.

对我来说很好用。

回答by Muthu Kumaran

Try this,

尝试这个,

$('#myselector').on('click', 'a', function(){
    var url = $(this).attr('href') //get url
    var arr = url.split('#');
    alert(arr[0]); //URL without hash #
    var hash = arr[1];
    console.log(hash);
})?