[英]How to redirect a user to another page with a button click using only JavaScript?
How to redirect a user to another page on a website using a linked JavaScript file, and how to convert the following line of code to non-embedded, linked JavaScript? 如何使用链接的JavaScript文件将用户重定向到网站上的其他页面,以及如何将以下代码行转换为非嵌入式链接JavaScript?
<button id="mybutton" type="button" onclick="myFunction()">Click me!</button>
HTML: HTML:
<button id="mybutton" type="button">Click me!</button>
JavaScript: JavaScript的:
function goToAnotherPage() {
window.location.assign("myotherpage.html");
}
function init() {
document.getElementById("mybutton").onclick = goToAnotherPage();
}
There are several ways to redirect users: 有几种方法可以重定向用户:
window.location.href
property window.location.href
属性 window.location.replace()
function window.location.replace()
函数 Create your buttons: 创建按钮:
<button id="my-button-1">Redirect 1</button>
<button id="my-button-2">Redirect 2</button>
Then, instead of using inline events, use event listeners in order to allow event delegation: 然后,使用事件侦听器而不是使用内联事件,以允许事件委派:
document.getElementById("my-button-1").addEventListener("click", function() {
window.location.replace("redirect/path/for/btn-1.html");
});
document.getElementById("my-button-2").addEventListener("click", function() {
window.location.replace("redirect/path/for/btn-2.html");
});
If you want to simulate a link click, use this instead: 如果您想模拟链接点击,请改用:
document.getElementById("my-button-1").addEventListener("click", function() {
window.location.href = "redirect/path/for/btn-1.html";
});
document.getElementById("my-button-2").addEventListener("click", function() {
window.location.href = "redirect/path/for/btn-2.html";
});
NOTE: The window.location.replace(...)
doesn't keep the originating page in the session history, this means that user won't have to click the back button to get back to where they were. 注意:
window.location.replace(...)
不会将原始页面保留在会话历史记录中,这意味着用户无需单击后退按钮即可返回到原来的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.