[英]How do I redirect to the current page using JavaScript?
單擊鏈接時,它應重定向到當前頁面。 我如何使用JavaScript執行此操作?
假設您的意思是鏈接應該刷新當前頁面,您可以使用window.location.reload()
。 在jQuery中它看起來像這樣:
<a href="#" id="myLink">Refresh current page</a>
$("#myLink").click(function() {
window.location.reload();
});
在普通JS中,它看起來像這樣:
document.querySelector("#myLink").addEventListener('click', function() {
window.location.reload();
});
這是一種使用vanilla JS而無需內聯並且沒有jQuery的方法:
<a href="#" id="myLink">Refresh current page</a>
<script>
document.querySelector("a#myLink").onclick = function(){
window.location.reload();
};
</script>
考慮使用querySelector()時請注意支持的瀏覽器列表
重定向到當前URL與重定向到任何URL是相同的:
// Same as clicking on a link
window.location.href = window.location.href;
// Same as HTTP redirecting
window.location.replace(window.location.href);
使用按鈕的示例:
<input type="button" value="Reload Page" onClick="window.location.reload()">
看這里:
http://www.mediacollege.com/internet/javascript/page/reload.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.