[英]Prevent page reloading continuously
我在函数内使用window.history.pushState({)
。 这按预期工作正常。 下面是一个示例。
$('#go_btn').click(function(){
if ($('.green')) {
var newurl = "cutomurl.html";
if(newurl!=window.location){
window.history.pushState({path:newurl},'',newurl);
}
return false;
}
});
并且我还获得了以下代码,当$('#go_btn')
按钮触发newurl
时,能够刷新页面。
$(window).on('popstate', function(){
location.reload(true);
});
在桌面版本上,我似乎没有任何问题。 但是,当我尝试在iPad上加载此页面时,它会不断地重新加载页面。 因此,如何仅在window.history.pushState({path:newurl},'',newurl);
时停止连续重新加载并使页面刷新 被触发了吗?
请注意,仅调用history.pushState()或history.replaceState()不会触发popstate事件。 仅通过执行浏览器操作(例如单击“后退”按钮(或在JavaScript中调用history.back()))才能触发popstate事件。 并且仅当用户在同一文档的两个历史记录条目之间导航时才触发该事件。
浏览器在页面加载时倾向于不同地处理popstate事件。 Chrome(v34之前的版本)和Safari始终在页面加载时发出popstate事件,但Firefox不会 。
根据Mozzila开发人员网络的说法
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate
Safari总是在页面加载时发出popstate事件。 这意味着
更新 :请阅读有关操纵浏览器历史记录的文档。 https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
您似乎误解了某些功能。
您有一个#go_btn按钮。 单击它时,您希望页面:
使用location.reload()
if (newurl != window.location)
{
// window.history.pushState({path:newurl},'',newurl);
location.reload(true);
}
使用location.href
。 它将在当前窗口中打开新页面 。
if (newurl != window.location)
{
// window.history.pushState({path:newurl},'',newurl);
location.href = newurl;
}
使用window.history.pushState()
或window.history.replaceState()
。 它不会打开新页面或重新加载它。 仅在您不打算导航但希望用户获得新的URL(方便浏览,历史记录或收藏夹)时使用。
if (newurl!=window.location)
{
window.history.pushState({path:newurl},'',newurl);
}
在所有三种情况下,您都不需要popstate
事件。 它用于其他目的。
您需要哪一个? 这取决于您的任务。
无论如何,将它们中的任何两个一起使用并不是不合逻辑和无用的。 如果要刷新页面,则推送历史记录状态的原因是什么? 然后导航到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.