js 实现href
实现 href 的 JavaScript 方法
在 JavaScript 中,可以通过多种方式实现类似 HTML 中 href 的功能,即跳转到指定 URL 或执行导航操作。
使用 window.location.href
通过修改 window.location.href 属性可以直接跳转到新的 URL:
window.location.href = "https://example.com";
使用 window.location.assign()
assign() 方法会加载新的文档并保留浏览历史:
window.location.assign("https://example.com");
使用 window.location.replace()
replace() 方法会替换当前页面,不会保留浏览历史:
window.location.replace("https://example.com");
动态创建 <a> 标签
可以通过 JavaScript 动态创建 <a> 标签并触发点击事件:
const link = document.createElement('a');
link.href = "https://example.com";
link.target = "_blank"; // 可选,在新标签页打开
link.click();
使用 window.open()
window.open() 方法可以在新窗口或标签页中打开 URL:
window.open("https://example.com", "_blank");
注意事项
- 使用
window.location的方法会在当前窗口导航到新页面。 window.open()可能被浏览器弹出窗口拦截器阻止。- 动态创建
<a>标签的方式更灵活,可以设置更多属性(如target)。







