无法使用jquery触发mousedown事件 [英] Cannot fire a mousedown event with jquery
问题描述
我正在尝试使用jquery模拟 http://translate.google.com 中的点击事件.为此,我使用以下代码加载了jquery文件:
I'm trying to simulate a click event in http://translate.google.com with jquery. For that purpose, I loaded jquery file with this code:
var script = document.createElement("script");
script.src = "http://code.jquery.com/jquery-1.10.1.min.js";
document.body.appendChild(script);
然后,我尝试使用选择器模拟对元素的点击,如下所示:
Then I'm trying to simulate a click on an element with a selector, like this:
jQuery(".goog-inline-block.goog-flat-menu-button-caption").trigger("mousedown")
我也尝试了此click事件,而不是按下mousedown:
I also tried this click event instead of mousedown:
jQuery(".goog-inline-block.goog-flat-menu-button-caption").trigger("click")
它们都不具有手动单击div的效果,即打开一个新的div.我附上了期望的行为.
None of them gives the effect of manually clicking to the div, namely opening a new div. I attached the ss of desired behaviour.
jquery无法正常工作的原因是什么?或如何以其他任何方式模拟效果?
What can be the cause for jquery not working? Or how can I simulate the effect in any other ways?
从某种意义上说,添加jQuery似乎是成功的,因为我可以使用jQuery方法来选择元素并更改其内容等.
Adding jQuery seems to be successful in the sense that I can use jQuery method to select elements and change contents of them etc.
推荐答案
解决方案是创建一个MouseEvent并将其分配到元素,如下所示:
The solution was creating a MouseEvent and dispatching it to the element, like this:
var e1 = document.createEvent("MouseEvents");
e1.initMouseEvent("mousedown", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
jQuery('#gt-sl-gms')[0].dispatchEvent(e1)
似乎jQuery的事件机制使用了不同的调度系统,因为它无法触发侦听器功能,尽管我没有确认此信息.
It seems jQuery's event mechanism uses a different dispatching system, since it can not trigger the listener function, though I didn't confirm this info.
这篇关于无法使用jquery触发mousedown事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!