HTML 原生点击事件
有没有一种方法可以在 javascript 中以编程方式调用标签的本机单击事件? .trigger('click') 或 .click() 函数将不起作用,因为它们触发链接的 onClick 事件,而不是 URL 后面的事件。我需要以编程方式单击隐藏链接,然后按照该链接转到同一浏览器中的新选项卡。 Window.open 也不起作用,因为这会导致弹出窗口,我试图避免这种情况。我需要这个,因为我在服务器端动态生成 URL 并通过 JSON 发送回响应。然后,我使用生成的 URL 填充隐藏链接的 HREF 属性。如果我能得到如何做到这一点的答案,我将不胜感激。
Is there a way to programmatically within javascript call the native click event of an tag? The .trigger('click') or .click() functions will not work, because they are triggering the onClick event of the link and not the event that follows the URL. I need to programmatically click a hidden link and follow that link to a new tab within the same browser. Window.open won't work either because that will cause a popup and I am trying to avoid that. I need this, because I am dynamically generating a URL on the server side and sending the responds back via JSON. I then populate the HREF attribute of the hidden link with the resulting URL. If I can get an answer on how this can be done, I would greatly appreciate it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用 JSON 响应填充 HREF,为什么不将其存储在变量中,然后当您想要访问它时,
window.location = yourVariable;
?If you're populating a HREF with the JSON response, why not just store it in a variable instead, and when you want to go to it,
window.location = yourVariable;
?除非您希望它仅在 IE 上运行,否则我无法为您提供答案,但我可以告诉您问题是什么。问题是
target=_blank
。尝试使用以下代码作为测试 - 请注意它会将您带到 Google.com - 然后尝试写入“_blank”作为目标。这似乎是浏览器唯一不允许的事情。您问题的部分答案是fireEvent()
适用于 IE,而dispatchEvent()
适用于其他所有内容。如果其他人可以改进此代码,我也将不胜感激更好的答案。Unless you want this to work on IE only, I don't have an answer for you, but I can tell you what the problem is. The problem is
target=_blank
. Try the following code as a test--notice it will bring you to Google.com--then try writing "_blank" in as the target. That seems to be the only thing that the browsers won't allow. A partial answer to your question isfireEvent()
works with IE anddispatchEvent()
works with everything else. If anyone else could improve on this code, I would appreciate a better answer as well.据我所知,不可能通过javascript调用链接的本机点击功能。您可以使用 .click() 引用 onclick,但本机单击仍将在调用之前运行。因此,如果您想在单击链接时更改该链接,然后再点击该链接,则必须单击该链接两次,然后它才会将您转到更改后的链接。
From what I can tell, it is not possible to call the native click function of a link through javascript. You can reference the onclick by using .click(), but the native click will still run before that is called. So, if you wanted to alter the link before following it when you click the link, you would have to click the link twice before it would send you to the altered link.