在 jQuery 中删除事件处理程序的最佳方法? [英] Best way to remove an event handler in jQuery?

查看:24
本文介绍了在 jQuery 中删除事件处理程序的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 input type="image".这就像 Microsoft Excel 中的单元格注释.如果有人在与此 input-image 配对的文本框中输入一个数字,我会为 input-image 设置一个事件处理程序.然后,当用户点击 image 时,他们会弹出一个小弹出窗口,为数据添加一些注释.

I have an input type="image". This acts like the cell notes in Microsoft Excel. If someone enters a number into the text box that this input-image is paired with, I setup an event handler for the input-image. Then when the user clicks the image, they get a little popup to add some notes to the data.

我的问题是,当用户在文本框中输入零时,我需要禁用 input-image 的事件处理程序.我尝试了以下方法,但无济于事.

My problem is that when a user enters a zero into the text box, I need to disable the input-image's event handler. I have tried the following, but to no avail.

$('#myimage').click(function { return false; });

推荐答案

jQuery ≥ 1.7

从 jQuery 1.7 开始,事件 API 已更新,.bind()/.unbind() 仍可用于向后兼容,但首选方法是使用on()/off() 函数.下面是,

jQuery ≥ 1.7

With jQuery 1.7 onward the event API has been updated, .bind()/.unbind() are still available for backwards compatibility, but the preferred method is using the on()/off() functions. The below would now be,

$('#myimage').click(function() { return false; }); // Adds another click event
$('#myimage').off('click');
$('#myimage').on('click.mynamespace', function() { /* Do stuff */ });
$('#myimage').off('click.mynamespace');

<小时>

jQuery <1.7

在您的示例代码中,您只是向图像添加另一个点击事件,而不是覆盖前一个:


jQuery < 1.7

In your example code you are simply adding another click event to the image, not overriding the previous one:

$('#myimage').click(function() { return false; }); // Adds another click event

这两个点击事件都会被触发.

Both click events will then get fired.

正如人们所说,您可以使用 unbind 删除所有点击事件:

As people have said you can use unbind to remove all click events:

$('#myimage').unbind('click');

如果您想添加单个事件然后将其删除(不删除可能已添加的任何其他事件),那么您可以使用事件命名空间:

If you want to add a single event and then remove it (without removing any others that might have been added) then you can use event namespacing:

$('#myimage').bind('click.mynamespace', function() { /* Do stuff */ });

并仅删除您的活动:

$('#myimage').unbind('click.mynamespace');

这篇关于在 jQuery 中删除事件处理程序的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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