简体   繁体   English

如何使用jQuery / Javascript模拟单击在新标签页/窗口中打开的链接?

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

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. 我希望能够从Java语言“单击”此内容。 I know I could do document.location=... but the problem here is the new tab part. 我知道我可以做document.location=...但是这里的问题是新标签页。 Is this possible? 这可能吗?

You can usually open a new window or tab using window.open . 通常,您可以使用window.open打开一个新窗口或选项卡 So instead of setting location , just call window.open and pass only the URL, nothing else. 因此,无需设置location ,只需调用window.open并仅传递URL,别无其他。

$("#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()

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()

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. 如果将函数绑定到click事件,则使用“ trigger”可以传递额外的参数。 See the jQuery 'trigger' documentation for more info: http://api.jquery.com/trigger/ 有关更多信息,请参见jQuery'trigger'文档。http : //api.jquery.com/trigger/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用JavaScript时,如何创建自动单击链接并在新标签页中打开它的代码? - When using JavaScript, how do I create code that automatically clicks a link and opens it in a new tab? 如何模拟用户单击JQuery中的链接? - How do I simulate user clicking a link in JQuery? 如何创建一个使用PHP打开新窗口的链接? - How do I create a link that opens up a new window with PHP? 当链接在新选项卡中打开时如何保留在当前窗口选项卡上 - How to stay on current window tab when the link opens in new tab 如何使用JavaScript打开新的选项卡/窗口? - How do I open a new tab/window using JavaScript? 如何在新选项卡中打开div链接Javascript onClick =“window.location - How do I make a div link open in a new tab Javascript onClick="window.location 如何使用jquery在新选项卡或窗口中捕获打开的链接? - how to capture open link in new tab or window using jquery? 单击链接后如何在新选项卡或窗口中显示内容 - How to show the content in a new tab or window after clicking on a link 如何打开新的浏览器窗口(不是选项卡),然后使用jQuery / Javascript调整其大小 - How to open new browser window (not tab) and then resize it using jQuery / Javascript 如何使用javascript / jQuery在新标签页中打开链接 - How to open a link in new tab using javascript/jQuery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM