从 URL 中获取哈希值

25
我试图在链接被点击后获取其哈希值。有任何想法吗?
例如:
这个链接
index.html#needThis

这是我的结果:

index.htmlneedThis

我如何移除 'index.html' 文件?

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

可能是 https://dev59.com/H3I-5IYBdhLWcg3wf4hD 的重复问题。您不需要“删除” index.html,而是只需获取哈希值即可。 - Nadav S.
为什么所有答案都使用 $(this).attr('href')?!尽可能使用本地JS:this.href具有完全相同的值,无需另一个库或函数调用。 - Martijn
5个回答

71

更新

现代浏览器(不确定多久之前的版本)可以直接从锚点元素中提取hash值(因此我添加了#5)。


任选其一...

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

更新

重新审视了这个问题,我认为#2可以进行改进:

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

如果没有哈希值存在,它将返回空值而不是整个URL。


第二个是完美的解决方案!没有异常:var hash = $(this).attr('href').replace(/^.*?#/,''); 谢谢 @Gaby - Bellash
@gaby,第三个解决方案中的test是什么? - Tobias Oberrauch
@TobiasOberrauch,好眼力...我已经纠正了...(本来应该是对href字符串的临时引用) - Gabriele Petrioli
@Bellash 刚刚对它进行了改进 :) - Gabriele Petrioli

16

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

它返回#后面的所有内容。

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

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

谢谢您的回复,但是对我来说不起作用,因为我需要被触发的a元素的href,而不是当前url。 :) - grindking
在这种情况下,使用a.substring(a.indexOf('#'))。 - Kirill Ivlev
4
window.location.hash实际上并没有“返回#后面的所有内容”,而是“返回从#开始的所有内容”,因此#符号也包含在内。 - Robo Robok

5
你可以尝试使用窗口位置哈希。
$('#myselector').on('click', 'a', function(){
    var hash = $(this).attr('href').replace('#', '') //get url
    var hash2 = window.location.hash ;
    console.log(hash2);
})

谢谢您,但是和上面的问题一样。 - grindking

2
为什么不直接使用以下方式:
window.location.hash

对我来说完全没问题。


1

试试这个,

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接