js 实现href
实现href跳转的方法
在JavaScript中实现类似<a href>的跳转功能有多种方式,以下列出常见方法:
使用window.location
直接修改window.location.href实现页面跳转:
window.location.href = "https://example.com";
使用location.assign()
通过location.assign()方法进行导航:

location.assign("https://example.com");
使用location.replace()
替换当前页面(不保留历史记录):
location.replace("https://example.com");
模拟点击a标签
动态创建并触发a标签点击:

const link = document.createElement('a');
link.href = "https://example.com";
link.click();
使用window.open()
在新窗口/标签页中打开链接:
window.open("https://example.com", "_blank");
注意事项
- 使用
replace()会跳过浏览器历史记录 - 部分浏览器可能拦截
window.open()的弹出窗口 - 现代前端框架推荐使用各自的路由系统(如React Router、Vue Router)处理导航
带参数的URL跳转
构建带查询参数的跳转链接:
const params = new URLSearchParams({ id: 123, page: 2 });
window.location.href = `https://example.com?${params.toString()}`;






