在Javascript中切换点击处理程序 [英] Toggling click handlers in Javascript

查看:123
本文介绍了在Javascript中切换点击处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML按钮,我附加一个事件,使用jQuery的 bind(),像这样:

I have an HTML button to which I attach an event, using jQuery's bind(), like so:

$('#mybutton').bind('click', myFirstHandlerFunction);

myFirstHandlerFunction 处理程序替换为新处理程序 mySecondHandlerFunction ,如下所示:

In myFirstHandlerFunction, I'd like this handler to replace itself with a new handler, mySecondHandlerFunction, like this:

function myFirstHandlerFunction(e) {
    $(this).unbind('click', myFirstHandlerFunction).bind('click', mySecondHandlerFunction);
}

在第二个点击处理程序中, mySecondHandlerFunction ,我想将按钮切换回其原始状态:解除绑定 mySecondHandlerFunction 处理程序并重新附加原始处理程序, myFirstHandlerFunction ,像这样:

In the second click handler, mySecondHandlerFunction, I'd like to toggle the button back to its original state: unbind the mySecondHandlerFunction handler and reattach the original handler, myFirstHandlerFunction, like so:

function mySecondHandlerFunction(e) {
    $(this).unbind('click', mySecondHandlerFunction).bind('click', myFirstHandlerFunction);
}

这很棒,除了一个小细节:因为点击事件没有但是通过每个按钮的点击处理程序传播,点击事件被传递到按钮的下一个点击处理程序,恰好是刚刚绑定在上一个处理程序中的处理程序。最终结果是 mySecondHandlerFunction 在执行 myFirstHandlerFunction 后立即执行。

This works great, except for one small detail: because the click event has not yet propagated through each of the button's click handlers, the click event is passed on to the button's next click handler, which happens to be the handler that was just bound in the previous handler. The end result is mySecondHandlerFunction being executed immediately after myFirstHandlerFunction is executed.

通过在每个处理程序中调用 e.stopPropagation()可以很容易地解决这个问题,但是这会产生消除任何其他点击处理程序的副作用

This problem can be easily solved by calling e.stopPropagation() in each handler, but this has the negative side-effect of cancelling any other click handlers that may have been attached independently.

有没有办法安全地并且一致地在两个点击处理程序之间切换,而不必停止点击事件的传播?

Is there a way to safely and and consistently toggle between two click handlers, without having to stop the propagation of the click event?

推荐答案


更新 toggle 在jQuery 1.9中删除,下面的解决方案不工作了。有关
替代方案,请参见此问题。 p>

Update: Since this form of toggle() was removed in jQuery 1.9, the solution below does not work anymore. See this question for alternatives.

它看起来像是 toggle()将会解决你的问题:

It looks like toggle() would solve your problem:

$("#mybutton").toggle(myFirstHandlerFunction, mySecondHandlerFunction);

上面的代码将注册 myFirstHandlerFunction code> mySecondHandlerFunction 在备用点击时调用。

The code above will register myFirstHandlerFunction and mySecondHandlerFunction to be called on alternate clicks.

这篇关于在Javascript中切换点击处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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