How do I refresh a page using JavaScript?
How do I refresh a page using JavaScript?
How do I refresh a page using JavaScript?
先自己寫寫看怎麼答,再往下對照重點答案。只存在你這台瀏覽器。
Use location.reload().
For example, to reload whenever an element with id="something" is clicked:
$('#something').click(function() {
location.reload();
});
The reload() function takes an optional parameter that can be set to true to force a reload from the server rather than the cache. The parameter defaults to false, so by default the page may reload from the browser's cache.
There are multiple unlimited ways to refresh a page with JavaScript:
location.reload()history.go(0)location.href = location.hreflocation.href = location.pathnamelocation.replace(location.pathname)location.reload(false)
If we needed to pull the document from the web-server again (such as where the document contents change dynamically) we would pass the argument as
true.
You can continue the list being creative:
window.location = window.locationwindow.self.window.self.window.window.location = window.locationvar methods = [
"location.reload()",
"history.go(0)",
"location.href = location.href",
"location.href = location.pathname",
"location.replace(location.pathname)",
"location.reload(false)"
];
var $body = $("body");
for (var i = 0; i < methods.length; ++i) {
(function(cMethod) {
$body.append($("<button>", {
text: cMethod
}).on("click", function() {
eval(cMethod); // don't blame me for using eval
}));
})(methods[i]);
}
button {
background: #2ecc71;
border: 0;
color: white;
font-weight: bold;
font-family: "Monaco", monospace;
padding: 10px;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.5s ease;
margin: 2px;
}
button:hover {
background: #27ae60;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This works on all browsers:
location.reload();