You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript修改相对路径无法正确跳转URL,如何模拟HTML的parent.location跳转行为?

问题根因

你写的代码和原HTML跳转逻辑有两处核心差异:

  • 原HTML操作的是父窗口的地址对象parent.location,你写的window.location是操作当前窗口
  • 原HTML赋值的是无前导斜杠的相对路径,浏览器会自动基于父窗口当前的基础路径拼接完整地址;你给pathname赋值时加了前导斜杠/,会强制识别为站点根目录下的绝对路径,直接丢失原有前置路径

正确实现代码

完全对齐原HTML逻辑的写法如下:

parent.location = 'page_confirm.html'

如果你实际需求是在当前窗口跳转而非父窗口,调整操作对象即可:

window.location = 'page_confirm.html'

可选稳妥写法

如果需要更可控的路径拼接,避免手动处理路径斜杠问题,可以用原生URL API实现:

// 父窗口跳转版本
const targetUrl = new URL('page_confirm.html', parent.location.href)
parent.location.href = targetUrl.href

// 当前窗口跳转版本
// const targetUrl = new URL('page_confirm.html', window.location.href)
// window.location.href = targetUrl.href

内容的提问来源于stack exchange,提问作者innom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 02:57:02