检测#符号后的网址更改

时间:2012-08-15 22:38:50

标签: javascript jquery html html5

我正在使用此代码知道#sign:

后网址中的内容
var a = document.URL.split("#")[1];

例如,如果网页的网址为http://example.com/path/to/somewhere/#contentpart,则变量a将包含contentpart

但问题是,用户可能会点击指向同一页面而另一部分的链接(例如:<a href="#footer">Go to footer</a>),如果是这样,页面将重新加载。 (只有页面会被导航到其他地方)

我的问题是,如何在同一页面的#符号后检测网址何时发生变化?

欢迎使用任何javascript / jQuery方法。

2 个答案:

答案 0 :(得分:4)

我建议,请记住您当前的代码:

$(window).on('hashchange', function(e){
    var newHash = document.href.split('#')[1];
});

虽然简单地使用它会更容易:

$(window).on('hashchange', function(e){
    var newHash = document.location.hash;
    console.log(newHash);
});

JS Fiddle demo

如果您不希望哈希包含#字符,请改用:

$(window).on('hashchange', function(e){
    var newHash = document.location.hash.substring(1);
    console.log(newHash);
});

JS Fiddle demo

答案 1 :(得分:2)

您可以通过获取window.location

hash属性来获取网址哈希
var a = window.location.hash;

对此属性的更改会在所有现代浏览器中触发hashchange事件。有关IE7及以下的解决方法包含在MDN文章中。

window.onhashchange = function (e) {
    // Manage changes to your page
    // You can also inspect e.newURL and e.oldURL if you need to

    // Optionally prevent window from scrolling to target
    e.preventDefault();
}

如果您正在使用jQuery,请查看jQuery BBQ。它包含了许多怪癖和浏览器兼容性问题,还允许您将更改推送到URL /历史记录状态,而不是依赖于用户单击链接。

相关问题