jQuery click()在Greasemonkey/Tampermonkey脚本中不起作用 [英] jQuery click() not working in a Greasemonkey/Tampermonkey script

查看:251
本文介绍了jQuery click()在Greasemonkey/Tampermonkey脚本中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在通过Greasemonkey/Tampermonkey触发jQuery单击时遇到问题...

I am having issues triggering a jQuery click through Greasemonkey/Tampermonkey...

jQuery('button').each(function() {
    jQuery(this).css('background', 'red');
    jQuery(this).click();
    location.assign("javascript:jQuery(this).click();void(0)");
}​

如您所见,我什至尝试了 location.assign hack ,但没有任何效果,没有控制台中的错误.

As you can see I've even tried the location.assign hack but nothing will work, no errors in the console either.

有趣的是,背景颜色确实变为红色,因此我假设它是.click()工作方式上与其他jQuery方法不同的东西.

Funny thing is that yes, the background colour does change to red so I am assuming it's something in the way .click() works that is different from other jQuery methods.

推荐答案

jQuery的.click()只是jQuery .trigger()

jQuery's .click() is just a shortcut for jQuery's .trigger() and from the Docs:

发生相应事件时,将触发任何附加有.bind()或其事件快捷方法之一的事件处理程序.可以使用.trigger()方法手动将其触发.

Any event handlers attached with .bind() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method.

这意味着不是由jQuery设置的事件处理程序不能总是由.click()(或.trigger())触发.

This means that event-handlers, that are not set by jQuery, cannot always be triggered by .click() (or .trigger()).

要解决此问题,请发送实际的鼠标事件:

To get around this, send actual mouse events:

jQuery ('button').each ( function () {
    jQuery (this).css ('background', 'red');

    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    this.dispatchEvent (clickEvent);
}





请注意,在极少数情况下,页面实际上可以处理多种事件,而不是click事件,并且从理论上讲,页面可以区分 任何 人工产生的事件(尽管我还没有在野外看到它).
如果是这种情况,请链接到目标页面,以便我们进行解决.

Note that in some rare cases, the page will actually work off a combination of events, not the click, and that theoretically, pages can discriminate against any artificially produced event (though I've yet to see that in the wild).
If that is the case here, link to the target page so that we can make workaround(s).

这篇关于jQuery click()在Greasemonkey/Tampermonkey脚本中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆