从url获取哈希值

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

例如

链接

index.html#needThis 

这是我的结果:

 index.htmlneedThis 

如何删除’index.html’?

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

更新

现代浏览器( 不确定它是怎么回事 )可以直接从锚元素中提取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 = window.location.hash

它在#之后返回一切

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

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

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

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

试试这个,

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

为什么不简单地使用:

 window.location.hash 

对我来说工作得很好。