如何覆盖 jquery 事件处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/741628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:41:29  来源:igfitidea点击:

How to overwrite jquery event handlers

jqueryevent-handling

提问by taras

I'll try to explain the problem with a simple code.

我会尝试用一个简单的代码来解释这个问题。

var fireClick = function() { alert('Wuala!!!') };

$('#clickme').click(fireclick);
$('#clickme').click(fireclick);

So now it will obviously alert 2 times but i need it alert only once. Tried so many ways, but no result.

所以现在它显然会发出 2 次警报,但我只需要它发出一次警报。尝试了很多方法,但没有结果。

Thanks.

谢谢。

回答by tvanfosson

As of jQuery 1.7 you should be using offto remove event handlers and onto add them, though you can still use the clickshorthand.

从 jQuery 1.7 开始,您应该使用off来删除事件处理程序并使用on来添加它们,尽管您仍然可以使用click速记。

$('#clickme').off('click').on('click', fireclick);
$('#clickme').off().on('click', fireclick);

Original answer:

原答案:

If you want to replace all click handlers, call unbindfirst without a function argument. If you want to replace all event handlers, don't specify the event type.

如果要替换所有单击处理程序,请先调用unbind而不使用函数参数。如果要替换所有事件处理程序,请不要指定事件类型。

$('#clickme').unbind('click').click(fireclick);
$('#clickme').unbind().click(fireclick);

回答by Neil Stevens

Use a namespace to make sure you don't remove any other listeners:

使用命名空间确保您不会删除任何其他侦听器:

$('#clickme').off('click.XXX').on('click.XXX', fireclick);

As long as no other code uses XXX, you can be sure that you have not messed up some other behaviour that you weren't aware of.

只要没有其他代码使用XXX,您就可以确定您没有搞砸一些您不知道的其他行为。

回答by moff

You may use the jQuery function unbindto remove the first event:

您可以使用 jQuery 函数unbind删除第一个事件:

var fireClick = function() { alert('Wuala!!!') };

$('#clickme').click(fireclick);
$('#clickme').unbind('click', fireClick); // fireClick won't fire anymore...
$('#clickme').click(fireclick); // ...but now it will

回答by Mark Renouf

I would try to eliminate the extra calls, but short of tyhat you could make sure to call both of these each time:

我会尝试消除额外的调用,但是如果没有 tyhat,您可以确保每次都调用这两个:

$('#clickme').unbind('click', fireclick);
$('#clickme').click(fireclick);

回答by Hassan Ejaz

$(document).off('click', '#clickme').on('click', '#clickme', fireclick);

回答by LeroyV

You should use setInterval. The problem is that you cannot have two alerts pop at the same time. First one has to close first or the second one can't appear on screen...

您应该使用 setInterval。问题是您不能同时弹出两个警报。第一个必须先关闭,否则第二个无法出现在屏幕上...