Javascript window.open 目标_self v window.location.href?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4813879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:13:39  来源:igfitidea点击:

window.open target _self v window.location.href?

javascript

提问by Rebecca

I need to redirect the user using JavaScript. Which is the preferred method?

我需要使用 JavaScript 重定向用户。哪种方法是首选?

window.open("webpage.htm", "_self");

or

或者

window.location.href = "webpage.htm";

回答by Jacob Relkin

Definitely the second method is preferred because you don't have the overhead of another function invocation:

绝对首选第二种方法,因为您没有另一个函数调用的开销:

window.location.href = "webpage.htm";

回答by Garry Polley

Hopefully someone else is saved by reading this.

希望其他人通过阅读这篇文章而得救。

We encountered an issue with webkit based browsers doing:

我们遇到了一个基于 webkit 的浏览器的问题:

window.open("webpage.htm", "_self");

The browser would lockup and die if we had too many DOM nodes. When we switched our code to following the accepted answer of:

如果我们有太多的 DOM 节点,浏览器就会死机。当我们将代码切换到以下接受的答案时:

location.href = "webpage.html";

all was good. It took us awhile to figure out what was causing the issue, since it wasn't obvious what made our page periodically fail to load.

一切都很好。我们花了一段时间才弄清楚是什么导致了这个问题,因为我们的页面周期性加载失败的原因并不明显。

回答by Frédéric Hamidi

As others have said, the second approach is usually preferred.

正如其他人所说,通常首选第二种方法。

The two code snippets are not exactly equivalent however: the first one actually sets window.openerto the window object itself, whereas the second will leave it as it is, at least under Firefox.

然而,这两个代码片段并不完全等效:第一个实际上设置window.opener为 window 对象本身,而第二个将保持原样,至少在 Firefox 下是这样。

回答by davidhiggins

You can omit windowand just use location.href. For example:

您可以省略window并仅使用location.href. 例如:

location.href = 'http://google.im/';

回答by Or Weinberger

window.location.href = "webpage.htm";

回答by Mohammed Shaheen MK

Please use this

请使用这个

window.open("url","_self"); 
  • The first parameter "url" is full path of which page you want to open.
  • The second parameter "_self", It's used for open page in same tab. You want open the page in another tab please use "_blank".
  • 第一个参数“url”是您要打开的页面的完整路径。
  • 第二个参数“_self”,用于在同一选项卡中打开页面。您想在另一个选项卡中打开页面,请使用“_blank”。