准備面試題目的時候遇到了頁面刷新,就整理了一下,網上查找,大概就是八種方法,但是自己測試的時候出現了幾個問題,跟大家分享:
首先准備一個測試頁面:
1 <!--html代碼--> 2 <h1 id="test">頁面刷新</h1> 3 <button onclick="fresh()">刷新</button
1 //script 2 var h1 = document.getElementById('test'); 3 function test(){ 4 h1.style.color = "red"; 5 h1.innerText = "我變化了"; 6 } 7 setInterval(test, 1000);
准備工作完成,開始頁面刷新方法:
1.可以正常使用的五種方法:
1 //第一種方法 2 function fresh(){ 3 window.location.reload();//強迫瀏覽器刷新當前頁面,默認參數為false,表示從客戶端緩存里取當前頁。如果指定為true,則以GET方式從服務端取最新的頁面,相當於客戶端點擊F5。 4 }
1 //第二種方法 2 function fresh(){ 3 history.go(0); 4 }
1 //第三種方法 2 function fresh(){ 3 location = location; 4 }
1 //第四種方法 2 function fresh(){ 3 location.assign(location);//assign()方法加載一個新的文檔。 4 }
1 //第五種方法 2 function fresh(){ 3 location.replace(location);//通過指定URL替換當前緩存在歷史里(客戶端)的項目,所以使用replace方法之后,不能通過“前進”和“后退”來訪問已經被替換的URL。 4 }
2.只在ie可以執行的兩種方法:
1 //第六種方法 2 function fresh(){ 3 document.execCommand('Refresh');//是只有IE提供的方法,叫瀏覽器方法。 4 }
1 //第七種方法 2 function fresh(){ 3 window.navigate(location);//只在ie可以執行,不適用於火狐等其他瀏覽器。 4 }
3.網上很容易找到,但是個人認為是錯誤的一種方法:
1 //錯誤方法 2 function fresh(){ 3 document.URL=location.href;//錯誤用法,document.URL只能讀不能寫 4 }
但是也可以有替代的方法:
1 //第八種方法 2 //window.location.href和document.location.href可以被賦值,然后跳轉到其它頁面 3 //一個窗口下只有一個window.location.href,但是可能有多個document.URL、document.location.href 4 function fresh(){ 5 document.location.href = location.href; 6 //可以使用,document表示的是一個文檔對象 7 }
1 //第九種方法(與第八種方法是一類) 2 function fresh(){ 3 window.location.href = location.href;//可以使用,window表示的是一個窗口對象 4 }
如有錯誤,請您指正!