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');
});
使用 <a> 标签模拟点击
动态创建或触发 <a> 标签的点击事件:
const link = document.createElement('a');
link.href = 'https://example.com';
link.target = '_blank'; // 可选:新标签页打开
link.click();
使用 location.assign() 跳转
location.assign() 会记录跳转历史,支持后退操作:
document.getElementById('button').addEventListener('click', function() {
location.assign('https://example.com');
});
使用 location.replace() 跳转(无历史记录)
直接替换当前页面,不保留历史记录:
document.getElementById('button').addEventListener('click', function() {
location.replace('https://example.com');
});
注意事项
- 跳转前可添加条件判断或异步操作(如确认弹窗)。
- 部分浏览器可能拦截
window.open()的弹出行为,需用户主动触发事件。







