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

我的问题是,当用户在文本框中输入0时,我需要禁用输入图像的事件处理程序。我试过以下方法,但都没用。

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

当前回答

希望我下面的代码说明一切。 HTML:

(function($){ $("#btn_add").on("click",function(){ $("#btn_click").on("click",added_handler); alert("Added new handler to button 1"); }); $("#btn_remove").on("click",function(){ $("#btn_click").off("click",added_handler); alert("Removed new handler to button 1"); }); function fixed_handler(){ alert("Fixed handler"); } function added_handler(){ alert("new handler"); } $("#btn_click").on("click",fixed_handler); $("#btn_fixed").on("click",fixed_handler); })(jQuery); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="btn_click">Button 1</button> <button id="btn_add">Add Handler</button> <button id="btn_remove">Remove Handler</button> <button id="btn_fixed">Fixed Handler</button>

其他回答

如果你通过html设置onclick,你需要removeAttr($(this).removeAttr('onclick'))

如果你通过jquery设置它(就像我上面例子中的第一次点击之后),那么你需要unbind($(this).unbind('click'))

这也很好。简单易行。参见http://jsfiddle.net/uZc8w/570/

$('#myimage').removeAttr("click");

如果你使用$(document).on()向动态创建的元素添加监听器,那么你可能必须使用以下方法来删除它:

// add the listener
$(document).on('click','.element',function(){
    // stuff
});

// remove the listener
$(document).off("click", ".element");

希望我下面的代码说明一切。 HTML:

(function($){ $("#btn_add").on("click",function(){ $("#btn_click").on("click",added_handler); alert("Added new handler to button 1"); }); $("#btn_remove").on("click",function(){ $("#btn_click").off("click",added_handler); alert("Removed new handler to button 1"); }); function fixed_handler(){ alert("Fixed handler"); } function added_handler(){ alert("new handler"); } $("#btn_click").on("click",fixed_handler); $("#btn_fixed").on("click",fixed_handler); })(jQuery); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="btn_click">Button 1</button> <button id="btn_add">Add Handler</button> <button id="btn_remove">Remove Handler</button> <button id="btn_fixed">Fixed Handler</button>

删除所有事件处理程序,这对我来说是有效的:

删除所有事件处理程序意味着使用纯HTML结构,而不将所有事件处理程序附加到元素及其子节点。为此,jQuery的clone()提供了帮助。

var original, clone;
// element with id my-div and its child nodes have some event-handlers
original = $('#my-div');
clone = original.clone();
//
original.replaceWith(clone);

这样,我们就有了一个没有事件处理程序的克隆版本来代替原始版本。

祝你好运…