Jquery 从url获取哈希值
我正在尝试在单击链接后获取哈希值。有什么想法吗 e、 g 链接Jquery 从url获取哈希值,jquery,url,hash,Jquery,Url,Hash,我正在尝试在单击链接后获取哈希值。有什么想法吗 e、 g 链接 index.html#needThis 这是我的结果: index.htmlneedThis 如何删除“index.html” $('#myselector').on('click', 'a', function(){ var hash = $(this).attr('href').replace('#', '') //get url console.log(hash); }) 只需使用var hash=win
index.html#needThis
这是我的结果:
index.htmlneedThis
如何删除“index.html”
$('#myselector').on('click', 'a', function(){
var hash = $(this).attr('href').replace('#', '') //get url
console.log(hash);
})
只需使用
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);
})
更新 现代浏览器(不知道它的历史如何)可以直接从锚元素中提取
散列(因此我添加了#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(/^.*?(#|$)/,'');
这样,如果不存在哈希,它将返回空而不是整个url。试试这个
$('#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
对我来说效果很好。谢谢,但在我的情况下它不起作用,因为我需要a元素的href,该元素是触发的,而不是来自当前url。:)在这种情况下,使用.substring(a.indexOf(“#”)window.location.hash实际上并不返回#之后的所有内容,而是从#开始的所有内容,因此包含#字符。的可能重复。您不需要“删除”index.html
,只需要获取散列。为什么所有答案都使用$(this.attr('href')
?!尽可能使用本机JS:this.href
具有完全相同的值,无需另一个库或函数调用。谢谢,但问题与上面相同。第二个是完美的解决方案!没有例外:var hash=$(this.attr('href').replace(/^.*?#/,'');多谢各位@Gaby@gaby3.什么是考试。解决方案?@TobiasOberrauch,大眼睛。。。我已经改正了。。。(这应该是对href
字符串的临时引用)@Bellash刚刚发布了一个改进:)