js按钮实现跳转
使用 window.location.href 跳转
通过修改 window.location.href 属性实现页面跳转,适用于简单场景:
document.getElementById("myButton").addEventListener("click", function() {
window.location.href = "https://example.com";
});
使用 window.open() 打开新窗口
在新标签页中打开目标链接,可通过参数控制窗口行为:
document.getElementById("myButton").addEventListener("click", function() {
window.open("https://example.com", "_blank");
});
通过 <a> 标签模拟按钮跳转
结合 HTML 和 CSS 实现按钮样式的链接跳转,语义更清晰:
<a href="https://example.com" class="button-style">点击跳转</a>
.button-style {
display: inline-block;
padding: 10px 20px;
background-color: #007bff;
color: white;
text-decoration: none;
border-radius: 5px;
}
使用 location.replace() 替换当前页
跳转后不保留当前页面的历史记录:
document.getElementById("myButton").addEventListener("click", function() {
location.replace("https://example.com");
});
动态传递参数的跳转
通过 URL 参数实现数据传递:
document.getElementById("myButton").addEventListener("click", function() {
const userId = 123;
window.location.href = `https://example.com/profile?id=${userId}`;
});
表单提交跳转
通过表单的 action 属性实现跳转,适合需要提交数据的场景:
<form action="https://example.com/login" method="POST">
<input type="text" name="username">
<button type="submit">提交并跳转</button>
</form>
路由跳转(前端框架示例)
适用于 Vue/React 等框架的路由跳转:
// Vue Router
this.$router.push("/target-path");
// React Router
import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
navigate("/target-path");






