从url获取哈希值

gri*_*ing 20 url hash jquery

我试图在点击链接后获取哈希值.有任何想法吗?

例如

链接

index.html#needThis
Run Code Online (Sandbox Code Playgroud)

这是我的结果:

index.htmlneedThis
Run Code Online (Sandbox Code Playgroud)

如何删除'index.html'?

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

Gab*_*oli 65

更新

现代浏览器(不知道它是怎么回事)可以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(/^.*?(#|$)/,'');
Run Code Online (Sandbox Code Playgroud)

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


Kir*_*lev 16

只是用var hash = window.location.hash.

它在#之后返回一切

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

$(this).attr('href').substring($(this).attr('href').indexOf('#'))
Run Code Online (Sandbox Code Playgroud)

  • `window.location.hash`实际上并不*返回#*之后的所有内容,但是*****从*#*开始,所以包含#字符. (3认同)

Was*_*ikh 5

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

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