js实现点击跳转
使用 window.location.href 实现跳转
通过修改 window.location.href 可以直接跳转到目标 URL。这是最常用的方法之一。
document.getElementById('button').addEventListener('click', function() {
window.location.href = 'https://example.com';
});
使用 window.open 实现新窗口跳转
如果需要在新标签页或新窗口中打开链接,可以使用 window.open 方法。
document.getElementById('button').addEventListener('click', function() {
window.open('https://example.com', '_blank');
});
使用 location.replace 实现替换当前页面
location.replace 会替换当前页面在浏览历史中的记录,用户无法通过后退按钮返回原页面。
document.getElementById('button').addEventListener('click', function() {
location.replace('https://example.com');
});
使用 location.assign 实现跳转
location.assign 会加载新的文档,并保留当前页面在浏览历史中,用户可以通过后退按钮返回。
document.getElementById('button').addEventListener('click', function() {
location.assign('https://example.com');
});
使用 <a> 标签模拟点击
通过 JavaScript 触发 <a> 标签的点击事件,实现跳转。
document.getElementById('button').addEventListener('click', function() {
const link = document.createElement('a');
link.href = 'https://example.com';
link.click();
});
使用 history.pushState 实现无刷新跳转
适用于单页应用(SPA),在不刷新页面的情况下修改 URL。
document.getElementById('button').addEventListener('click', function() {
history.pushState({}, '', '/new-page');
});
使用 form 提交实现跳转
通过 JavaScript 提交表单,实现跳转。
document.getElementById('button').addEventListener('click', function() {
const form = document.createElement('form');
form.method = 'GET';
form.action = 'https://example.com';
document.body.appendChild(form);
form.submit();
});
注意事项
- 使用
window.open可能会被浏览器拦截为弹窗,需确保用户主动触发。 location.replace和location.assign的区别在于是否保留历史记录。- 单页应用推荐使用
history.pushState或路由库(如 React Router、Vue Router)。







