js按钮实现跳转
使用 window.location.href 实现跳转
通过修改 window.location.href 属性可以直接跳转到指定 URL:
document.getElementById("myButton").addEventListener("click", function() {
window.location.href = "https://example.com";
});
使用 window.open() 打开新窗口
如果需要在新标签页中打开链接,可以使用 window.open():

document.getElementById("myButton").addEventListener("click", function() {
window.open("https://example.com", "_blank");
});
通过 <a> 标签模拟按钮跳转
结合 HTML 和 CSS 将 <a> 标签样式设置为按钮,保留原生跳转功能:
<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");
});
动态传递参数跳转
在跳转时携带查询参数:
document.getElementById("myButton").addEventListener("click", function() {
const userId = 123;
window.location.href = `https://example.com/profile?id=${userId}`;
});
表单提交跳转
通过表单的 action 属性实现跳转(适合需要提交数据的场景):
<form id="redirectForm" action="https://example.com" method="GET">
<input type="hidden" name="source" value="button">
<button type="submit">跳转</button>
</form>
注意事项
- 使用
window.open()可能会被浏览器拦截弹窗,需确保由用户主动触发(如click事件)。 - 跳转前可添加条件判断(如数据验证):
if (isValid) { window.location.href = "https://example.com"; }






