如何获取JQuery.trigger('click');启动鼠标单击 [英] How to get JQuery.trigger('click'); to initiate a mouse click
问题描述
我很难理解如何使用JQuery模拟鼠标单击.有人可以告诉我我做错了什么吗.
I'm having a hard time understand how to simulate a mouse click using JQuery. Can someone please inform me as to what i'm doing wrong.
HTML:
<a id="bar" href="http://stackoverflow.com" target="_blank">Don't click me!</a>
<span id="foo">Click me!</span>
jQuery:
jQuery('#foo').on('click', function(){
jQuery('#bar').trigger('click');
});
演示: FIDDLE
当我单击#foo按钮时,我想模拟一次对#bar的单击,但是当我尝试这样做时,什么也没有发生.我也尝试了jQuery(document).ready(function(){...})
,但没有成功.
when I click on button #foo I want to simulate a click on #bar however when I attempt this, nothing happens. I also tried jQuery(document).ready(function(){...})
but without success.
推荐答案
您需要使用jQuery('#bar')[0].click();
You need to use jQuery('#bar')[0].click();
to simulate a mouse click on the actual DOM element (not the jQuery object), instead of using the .trigger()
jQuery method.
注意:DOM 2级.click()
在上不起作用Safari中的一些元素.您将需要使用解决方法.
Note: DOM Level 2 .click()
doesn't work on some elements in Safari. You will need to use a workaround.
这篇关于如何获取JQuery.trigger('click');启动鼠标单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!