哪一个更好的方法是window.parent.location.href或window.top.location

Has*_*tar 7 javascript jquery

我正在一个项目中工作,我必须在特定场景中重定向错误页面.为此,我创建了Error.aspx页面.现在我正在使用window.top.location.href ="../ Error.aspx"并生成http://localhost/app_web/Error.aspx 并且它的工作正常,除了一次(显示消息http:// xyz) /ErrorPage.aspx '不存在.).所以任何人都可以建议哪个是更好的选择.

谢谢

Nie*_*sol 10

topparent如果您的目的是将页面放到最顶层,那么"比"更好,因为您的页面可能位于框架内部的框架内.

至于你的相对路径问题,你可能想尝试:

var local = location.pathname.split("/");
local.pop(); // remove the filename
local.pop(); // remove the containing directory
local.push("Error.aspx");
local = location.protocol+"//"+location.hostname+"/"+local.join("/");
top.location.href = local;
Run Code Online (Sandbox Code Playgroud)


Mat*_*att 9

window.parent指的是当前窗口的父窗口.那个父母可能拥有自己的父母,父母有自己的父母等.

window.top指的是这个最顶层的窗口; 例如window.parent.parent.parent[...];

但是,在这种情况下,您可能只想重定向当前窗口,例如;

window.location.href = "../Error.aspx";
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息,请参阅该文档window.parent,window.topwindow.location.


Sta*_*arx 6

这取决于你想要做什么.

  1. window.parent.location

    用于更改父窗口的位置.

  2. window.top.location

    • 它是对象"窗口"的属性.
    • 它返回窗口层次结构中最顶层窗口的位置.
    • 如果窗口没有父级,则top是对自身的引用(window === window.top)