无法以编程方式触发jQuery点击事件 [英] Cannot programmatically trigger jQuery click event

查看:103
本文介绍了无法以编程方式触发jQuery点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我理解正确,以编程方式触发一个附加到css类 my-button 的对象的jQuery点击事件,你应该可以这样做:

If I understand correctly, to programmatically trigger a jQuery click event attached to an object with a css class of my-button, you should be able to just do this:

$('.my-button').click();

由于某些原因,此代码无法触发元素附加的点击事件。代码的 $('。my-button')部分正在工作并返回一个元素。我们知道事件处理程序附加到该元素,因为单击该元素不会触发其事件处理程序的代码。处理程序附有以下简单代码:

For some reason, this code is failing to trigger the click event attached to the element. The $('.my-button') part of the code is working and returning one element. We know the event handler is attached to that element because clicking on the element does trigger its event handler's code. The handler is attached with the following simple code:

$('<a class="my-button"/>')
    .click(function() { /* code here */ })
    .appendTo(parent);

是否存在事件触发不起作用的任何条件?正在访问的元素是通过jQuery小部件创建的,小部件代码通过跨域JSONP调用并通过 eval (我怀疑的因素)进行检索。

Are there any conditions where event triggering does not work? The element being accessed is created through a jQuery widget, the widget code is retrieved through a cross-domain JSONP call and run through eval (the factor I suspect).

推荐答案

这是一个两个jQuery脚本加载的情况。通过JSONP检索的脚本包括加载jQuery,并且jQuery对象用于附加事件处理程序。同时,在我的同事的网页上,他加载了自己的jQuery。因此,这个第二个jQuery对象,不知道第一个事件处理程序,无法以编程方式调用处理程序。

This turned out to be a case of two jQuery scripts being loaded. The script retrieved via JSONP included the loading of jQuery, and that jQuery object was used to attach the event handler. Meanwhile, in my co-worker's web page, he had loaded his own jQuery. Therefore, this second jQuery object, having no knowledge of the first's event handlers, was unable to programmatically invoke the handler.

这篇关于无法以编程方式触发jQuery点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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