如何使用 jQuery/Javascript 模拟单击​​在新选项卡/窗口中打开的链接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8160702/
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-10-26 02:29:47  来源:igfitidea点击:

How do I simulate clicking a link that opens in a new tab/window using jQuery/Javascript?

javascriptjqueryhtmlbrowser

提问by izb

I have a link that opens in a new tab with _blank:

我有一个链接,可以在带有 _blank 的新选项卡中打开:

<a href="new_page.html" target="_blank">link</a>

I'd like to be able to 'click' on this from Javascript. I know I could do document.location=...but the problem here is the new tab part. Is this possible?

我希望能够从 Javascript 中“点击”这个。我知道我可以做,document.location=...但这里的问题是新标签部分。这可能吗?

回答by Ry-

You can usually open a new window or tabusing window.open. So instead of setting location, just call window.openand pass only the URL, nothing else.

您通常可以使用.打开一个新窗口或选项卡window.open。因此,不要设置location,只需调用window.open并传递 URL,别无其他。

回答by Willy Carman

$("#your_a").click(function(e) {
   e.preventDefault();
   window.open($(this).attr("href"), this.target);
}

You could use any name for target, preventDefault()if you want to override the link actions completely

preventDefault()如果您想完全覆盖链接操作,您可以使用任何名称作为目标

回答by R G

If you really want to simulate click, you can give a id to the anchor tag and call jQuery click() on that element.

如果你真的想模拟点击,你可以给锚标记一个 id 并在该元素上调用 jQuery click()。

<a id="mylink" href="new_page.html" target="_blank">link</a>

and in script

并在脚本中

$("#mylink").click()

回答by Mike Taylor

to "simulate" the click you trigger the click event:

要“模拟”您触发点击事件的点击:

HTML:

HTML:

<a href="new_page.html" target="_blank" id="mylink">click me</a>

jQuery:

jQuery:

$("#mylink").trigger("click");

-or-

-或者-

$("#mylink").click();

Using 'trigger' allows you to pass in extra parameters if you bind a function to the click event. See the jQuery 'trigger' documentation for more info: http://api.jquery.com/trigger/

如果将函数绑定到单击事件,则使用 'trigger' 允许您传入额外的参数。有关更多信息,请参阅 jQuery 'trigger' 文档:http: //api.jquery.com/trigger/