Tom*_*ter 60 javascript navigation ajax fragment-identifier hashchange
我刚在http://ritter.vg上设置了我的新主页.我正在使用jQuery,但非常简单.
它使用AJAX加载所有页面 - 我将其设置为通过检测URL中的哈希来允许书签.
//general functions
function getUrl(u) {
return u + '.html';
}
function loadURL(u) {
$.get(getUrl(u), function(r){
$('#main').html(r);
}
);
}
//allows bookmarking
var hash = new String(document.location).indexOf("#");
if(hash > 0)
{
page = new String(document.location).substring(hash + 1);
if(page.length > 1)
loadURL(page);
else
loadURL('news');
}
else
loadURL('news');
Run Code Online (Sandbox Code Playgroud)
但我不能让后退和前进按钮工作.
有没有办法检测何时按下后退按钮(或检测哈希值何时更改)而不使用setInterval循环?当我尝试使用.2和1秒超时时,它固定了我的CPU.
Dre*_*kes 46
这里的答案都很古老.
在HTML5世界中,您应该使用onpopstate
事件.
window.onpopstate = function(event)
{
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
Run Code Online (Sandbox Code Playgroud)
要么:
window.addEventListener('popstate', function(event)
{
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
});
Run Code Online (Sandbox Code Playgroud)
后一个片段允许存在多个事件处理程序,而前者将替换任何可能导致难以发现的错误的现有处理程序.
bal*_*ton 11
HTML5包含了比使用hashchange更好的解决方案,这是HTML5状态管理API - https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history - 它们允许您更改页面的URL,而无需使用哈希!
虽然HTML5状态功能仅适用于HTML5浏览器.所以你可能想要使用像History.js这样的东西,它为HTML4浏览器提供向后兼容的体验(通过哈希,但仍然支持数据和标题以及replaceState功能).
你可以在这里阅读更多相关信息:https: //github.com/browserstate/History.js