我可以触发点击事件onload [英] can I trigger click event onload
问题描述
我的页面中有锚标记。我喜欢触发click事件onload。这意味着我想用新标签打开这个页面http://XXXXX.com。因为我不想弹出阻挡者。反正有没有这样做?
I am having anchor tag in my page. I like to trigger click event onload . Which means I wanna open this page "http://XXXXX.com" with new tab. Because I don't wanna popup blockers. Is there anyway to do this?
锚定器如下所示
id="add_redirect"
href="http://XXXXX.com"
target="_blank"
推荐答案
如果您的目标是在页面加载时绕过弹出窗口阻止程序,则触发单击
事件合成可能不会起作用。浏览器非常聪明,可以知道用户生成的点击
何时调用点击
函数DOM元素(在那些浏览器上甚至可以工作)。示例: http://jsbin.com/avibi3/3 , http://jsbin.com/avibi3/4
If your goal is to bypass pop-up blockers on page load, triggering the click
event synthetically probably won't work. Browsers are smart enough to know when a click
is user-generated vs. when you've called the click
function on the DOM element (on those browsers were that even works). Examples: http://jsbin.com/avibi3/3, http://jsbin.com/avibi3/4
使用jQuery的触发器
机制当然不会这样做,因为它根本没有真正触发点击
事件;它只是触发jQuery连接的处理程序(编辑:显然,通过 onclick
属性定义的&mbsp;—参见Sukhi的回答 —但不是通过 addEventListener
)附加。如果你想做什么,Sukhi的答案会告诉你如何,虽然我总是说:如果你想要从两个不同的地方运行代码,把它放在一个函数中,并从两个不同的地方调用该函数(而不是把它放在一起)在中单击
处理程序,然后模拟单击以运行代码)。 触发器的有效用例
(主要与第三方脚本集成有关),但是为了从两个不同的地方运行自己的代码,这是设计问题的症状。
Using jQuery's trigger
mechanism certainly won't do it, because it doesn't really trigger a click
event at all; it just fires the handlers that jQuery hooked up (edit: and, apparently, ones defined via an onclick
attribute — see Sukhi's answer — but not ones attached via addEventListener
). If that's what you want to do, Sukhi's answer shows you how, although I always say: If you want code to be run from two different places, put it in a function, and call that function from two different places (rather than putting it in a click
handler and then simulating a click just to run the code). There are valid use cases for trigger
(mostly relating to integrating with third-party scripts), but for running your own code from two different places, it's a symptom of a design problem.
这篇关于我可以触发点击事件onload的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!