Home > Web Front-end > JS Tutorial > body text

js page refresh to achieve ordinary page

高洛峰
Release: 2016-10-12 11:24:10
Original
1020 people have browsed it

When I was preparing the interview questions, I encountered a page refresh, so I sorted it out and searched online. There were about eight methods. However, when I tested it, I encountered several problems. I would like to share with you:

First prepare a test page:

<!--html代码--> 
<h1 id="test">页面刷新</h1>
<button onclick="fresh()">刷新</button
Copy after login
//script
var h1 = document.getElementById(&#39;test&#39;);
function test(){
     h1.style.color = "red";
     h1.innerText = "我变化了";
}
setInterval(test, 1000);
Copy after login

Preparation work is completed, start the page refresh method:

  1. Five methods that can be used normally:

 //第一种方法
function fresh(){
       window.location.reload();//强迫浏览器刷新当前页面,默认参数为false,表示从客户端缓存里取当前页。如果指定为true,则以GET方式从服务端取最新的页面,相当于客户端点击F5。
}
Copy after login
 //第二种方法
 function fresh(){
      history.go(0);
}
Copy after login
 //第三种方法
 function fresh(){
       location = location;
 }
Copy after login
 //第四种方法
 function fresh(){
       location.assign(location);//assign()方法加载一个新的文档。
 }
Copy after login
 //第五种方法
 function fresh(){
     location.replace(location);//通过指定URL替换当前缓存在历史里(客户端)的项目,所以使用replace方法之后,不能通过“前进”和“后退”来访问已经被替换的URL。
 }
Copy after login

2. Two methods that can only be executed in IE:

 //第六种方法
 function fresh(){
       document.execCommand(&#39;Refresh&#39;);//是只有IE提供的方法,叫浏览器方法。
 }
Copy after login
 //第七种方法
 function fresh(){
       window.navigate(location);//只在ie可以执行,不适用于火狐等其他浏览器。
 }
Copy after login

3. It is easy to find online, but Personally I think this is the wrong method:

 //错误方法
 function fresh(){
       document.URL=location.href;//错误用法,document.URL只能读不能写
 }
Copy after login

But there is also an alternative method:

//第八种方法
//window.location.href和document.location.href可以被赋值,然后跳转到其它页面
//一个窗口下只有一个window.location.href,但是可能有多个document.URL、document.location.href
function fresh(){
      document.location.href = location.href;
      //可以使用,document表示的是一个文档对象   
}
Copy after login
 //第九种方法(与第八种方法是一类)
 function fresh(){
      window.location.href = location.href;//可以使用,window表示的是一个窗口对象
 }
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template