我试图在点击链接后获取哈希值.有任何想法吗?
例如
链接
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)
随便挑选..
var hash = $(this).attr('href').split('#')[1];
var hash = $(this).attr('href').replace(/^.*?#/,'');
var href = $(this).attr('href'), hash = href.substr(href.indexOf('#')+1);
var hash = $(this).attr('href').match(/#(.*$)/)[1];
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)
您可以尝试使用窗口位置哈希.
$('#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)