jQuery:如何触发锚链接的点击事件
我有一个锚链接,例如
<a id="myanchor" href="http://google.com" target="_blank">Google</a>
如何以编程方式在新选项卡中打开 href 目标?
I have a anchor link like
<a id="myanchor" href="http://google.com" target="_blank">Google</a>
How to open href target in a new tab programatically?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
请尝试以下操作:
$("#myanchor")[0].click()
就这么简单。
Try the following:
$("#myanchor")[0].click()
As simple as that.
调用
click
事件(不执行重定向)和导航到href
位置是有区别的。导航:
在新选项卡或窗口中打开:
调用单击事件(调用 javascript):
There's a difference in invoking the
click
event (does not do the redirect), and navigating to thehref
location.Navigate:
Open in new tab or window:
invoke click event (call the javascript):
尽管这篇文章是 caput 的,但我认为它很好地演示了 jQuery 可能遇到的一些障碍,即认为
click()
实际上单击了一个元素,而不是仅仅发送一个单击事件冒泡通过 DOM 向上。假设您实际上需要模拟点击事件(即出于测试目的等)。如果是这样,只要您使用的是现代浏览器,您就可以使用HTMLElement.prototype .click
(请参阅此处了解方法详细信息以及链接到W3规格)。这应该适用于几乎所有浏览器,特别是如果您正在处理链接,并且如果您需要的话,您可以很容易地返回到window.open
:Even though this post is caput, I think it's an excellent demonstration of some walls that one can run into with jQuery, i.e. thinking
click()
actually clicks on an element, rather than just sending a click event bubbling up through the DOM. Let's say you actually need to simulate a click event (i.e. for testing purposes, etc.) If that's the case, provided that you're using a modern browser you can just useHTMLElement.prototype.click
(see here for method details as well as a link to the W3 spec). This should work on almost all browsers, especially if you're dealing with links, and you can fall back towindow.open
pretty easily if you need to:它对我有用:
It worked for me:
您无法以编程方式在新选项卡中打开,这是浏览器功能。您可以在外部窗口中打开链接。看看这里
You cannot open in a new tab programmatically, it's a browser functionality. You can open a link in an external window . Have a look here