如何使用 JavaScript 或 jQuery 在新选项卡中打开 URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19851782/
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
How to open a URL in a new Tab using JavaScript or jQuery?
提问by Midhuna
How to open a URL in new tab instead of new window programatically?
如何以编程方式在新选项卡而不是新窗口中打开 URL?
回答by FabianCook
Use window.open()
:
使用window.open()
:
var win = window.open('http://stackoverflow.com/', '_blank');
if (win) {
//Browser has allowed it to be opened
win.focus();
} else {
//Browser has blocked it
alert('Please allow popups for this website');
}
Depending on the browsers implementation this will work
根据浏览器的实现,这将起作用
There is nothing you can do to make it open in a window rather than a tab.
您无法在窗口而不是选项卡中打开它。
回答by JaiSat
This is as simple as this.
这就是如此简单。
window.open('_link is here_', 'name');
Function description:
功能说明:
name
is a name of the window. Following names are supported:
name
是窗口的名称。支持以下名称:
_blank
- URL is loaded into a new tab. This is default._parent
- URL is loaded into the parent frame_self
- URL replaces the current page_top
- URL replaces any framesets that may be loaded
_blank
- URL 加载到新选项卡中。这是默认设置。_parent
- URL 加载到父框架中_self
- URL 替换当前页面_top
- URL 替换可能加载的任何框架集
回答by Lafif Astahdziq
if you mean to opening all links on new tab, try to use this jquery
如果您打算在新选项卡上打开所有链接,请尝试使用此 jquery
$(document).on('click', 'a', function(e){
e.preventDefault();
var url = $(this).attr('href');
window.open(url, '_blank');
});
回答by codebreaker
var url = "http://www.example.com";
window.open(url, '_blank');
回答by Koffy
You can easily create a new tab; do like the following:
您可以轻松创建一个新选项卡;请执行以下操作:
function newTab() {
var form = document.createElement("form");
form.method = "GET";
form.action = "http://www.example.com";
form.target = "_blank";
document.body.appendChild(form);
form.submit();
}
回答by Daniel Falabella
I know your question does not specify if you are trying to open all a tags in a new window or only the external links.
我知道您的问题没有说明您是要在新窗口中打开所有标签还是仅打开外部链接。
But in case you only want external links to open in a new tab you can do this:
但如果您只想在新选项卡中打开外部链接,您可以这样做:
$( 'a[href^="http://"]' ).attr( 'target','_blank' )
$( 'a[href^="https://"]' ).attr( 'target','_blank' )