JS 实现页面跳转的几种方式总结
warning:
这篇文章距离上次修改已过441天,其中的内容可能已经有所变动。
在JavaScript中,实现页面跳转主要有以下几种方式:
- 使用
window.location.href:
window.location.href = 'https://www.example.com';- 使用
window.location.assign:
window.location.assign('https://www.example.com');- 使用
window.location.replace(不推荐,因为它不会在历史记录中留下当前页面):
window.location.replace('https://www.example.com');- 使用
window.location.reload(重新加载当前页面,可以带参数决定是否清空缓存):
// 重新加载当前页面,不清空缓存
window.location.reload(false);
// 重新加载当前页面,清空缓存
window.location.reload(true);- 使用
location.href和location.replace(与window.location.href和window.location.replace类似):
location.href = 'https://www.example.com';
location.replace('https://www.example.com');- 使用
document.forms和target="_blank"(在新标签页打开链接):
<form id="jumpForm" action="https://www.example.com" method="get" target="_blank">
<!-- 可以添加隐藏的表单字段 -->
</form>
<script>
document.getElementById('jumpForm').submit();
</script>- 使用
a标签的点击事件(在同一标签页打开链接):
<a id="jumpLink" href="https://www.example.com" target="_self">跳转到示例页面</a>
<script>
document.getElementById('jumpLink').click();
</script>以上方法可以实现页面跳转,你可以根据实际需求选择合适的方式。
评论已关闭