在jQuery中控制顺序触发的Click UI事件 [英] Control the order triggered click UI events in jQuery

查看:143
本文介绍了在jQuery中控制顺序触发的Click UI事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个<input type="checkbox" />,它具有通过jQuery的.click函数绑定的单击处理程序.然后根据其状态执行一些计算:

I have a <input type="checkbox" /> which has a click handler bound to it via jQuery's .click function. It then performs some calculations depending on its state:

$(':checkbox').click(function () {
    if (this.checked) {
        console.log("ACTIVE");
    } else {
        console.log("INACTIVE");
    }
});

在UI中这一切都很好,但是,在我的单元测试中,我想模拟对此元素的单击并确保运行正确的代码.

That's all good in the UI, however, in my unit tests, I want to simulate a click on this element and make sure the correct code is run.

$(testElement).click();

问题在于默认浏览器操作在之前调用了该处理程序,因此this.checked的值被颠倒了.也就是说,直到我的处理程序运行之后,它的checked属性才会更改.

The problem is that the handler is called before the default browser action, and so the values of this.checked are reversed. That is, it doesn't get its checked attribute changed until after my handler runs.

有什么办法解决吗?我可以绑定其他事件吗?是否可以通过其他方式以编程方式触发点击?

Is there any way around this? Is there a different event I could bind to? Is there a different way to trigger the clicks programmatically?

推荐答案

查看此

Looking at this blog post you might be able to get the behavior your are looking at by doing the following:

$( ":checkbox" )[ 0 ].checked = !$( ":checkbox" )[ 0 ].checked;
$(":checkbox" ).triggerHandler( "click" );

并且使用 triggerHandler() ,您将仅触发受jQuery约束的事件,而不会触发默认行为.

And with the use of triggerHandler(), you will only trigger events bound by jQuery and not the default behavior.

jsfiddle 上的代码示例.

Code example on jsfiddle.

这篇关于在jQuery中控制顺序触发的Click UI事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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