js实现跳转到新的页面
实现页面跳转的方法
在JavaScript中,可以通过多种方式实现页面跳转。以下是几种常见的方法:
使用 window.location.href
通过修改 window.location.href 属性可以直接跳转到新的URL:
window.location.href = 'https://example.com';
使用 window.location.replace
replace 方法会替换当前页面,不会在浏览历史中留下记录:

window.location.replace('https://example.com');
使用 window.open
在新标签页或窗口中打开页面:
window.open('https://example.com', '_blank');
使用 location.assign
assign 方法会加载新的文档并保留浏览历史:

window.location.assign('https://example.com');
使用表单提交
通过动态创建表单并提交实现跳转:
const form = document.createElement('form');
form.method = 'GET';
form.action = 'https://example.com';
document.body.appendChild(form);
form.submit();
使用 <a> 标签
模拟点击链接实现跳转:
const link = document.createElement('a');
link.href = 'https://example.com';
link.click();
注意事项
- 使用
window.open可能会被浏览器拦截,需确保是由用户触发的操作。 replace方法不会在历史记录中留下痕迹,适用于不希望用户返回的场景。- 跨域跳转需遵循同源策略,某些操作可能受限。






