[英]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.