在Javascript中切换点击处理程序 [英] Toggling click handlers in Javascript
问题描述
bind()
,像这样: $('#mybutton')。bind('click',myFirstHandlerFunction);
在 myFirstHandlerFunction
中,我想要处理程序用一个新的处理程序替换它, mySecondHandlerFunction
,像这样:
function myFirstHandlerFunction(e){
$(this).unbind('click',myFirstHandlerFunction).bind('click',mySecondHandlerFunction);
}
在第二个点击处理程序中, mySecondHandlerFunction
,我想将按钮切换回原始状态:取消绑定 mySecondHandlerFunction
处理程序并重新挂接原始处理程序, myFirstHandlerFunction
,像这样:
function mySecondHandlerFunction(e){
$(this).unbind ('click',mySecondHandlerFunction).bind('click',myFirstHandlerFunction);
}
除了一个小细节,这是非常好的,因为点击事件没有但是通过每个按钮的点击处理程序传播,点击事件被传递到按钮的下一个点击处理程序,这恰好是刚刚绑定在前一个处理程序中的处理程序。最终结果是执行 myFirstHandlerFunction
后立即执行的 mySecondHandlerFunction
。
通过在每个处理程序中调用 e.stopPropagation()
可以很容易地解决这个问题,但是这会消除任何其他点击处理程序的副作用,已经独立附加。
有没有办法安全和一致地在两个点击处理程序之间切换,而不必停止点击事件的传播?
更新:由于此形式的
toggle()
在jQuery 1.9中被删除,下面的解决方案不再工作了。有关
替代方案,请参见此问题。 p>
它看起来像 toggle()将解决您的问题:
$(#mybutton)。toggle(myFirstHandlerFunction,mySecondHandlerFunction );
上面的代码将注册 myFirstHandlerFunction
code> mySecondHandlerFunction 可以进行备用点击。
I have an HTML button to which I attach an event, using jQuery's bind()
, like so:
$('#mybutton').bind('click', myFirstHandlerFunction);
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);
}
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);
}
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.
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?
Update: Since this form of
toggle()
was removed in jQuery 1.9, the solution below does not work anymore. See this question for alternatives.
It looks like toggle() would solve your problem:
$("#mybutton").toggle(myFirstHandlerFunction, mySecondHandlerFunction);
The code above will register myFirstHandlerFunction
and mySecondHandlerFunction
to be called on alternate clicks.
这篇关于在Javascript中切换点击处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!