问题描述
我有一个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
在示例代码中,您只是向图像添加了另一个click事件,而不是覆盖前一个事件:
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.
正如人们所说,您可以使用取消绑定删除所有点击事件:
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中删除事件处理程序的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!