如何清除Jquery中的所有Click事件处理程序 [英] How to remove all Click event handlers in Jquery

查看:208
本文介绍了如何清除Jquery中的所有Click事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题。基本上,当用户点击网页上的修改链接时,以下Jquery代码会运行:

  $(#saveBtn ).click(function(){
saveQuestion(id);
});

通过这样做,保存按钮的onClick事件调用 saveQuestion )方法,并传递单击编辑链接的问题的ID。



但是如果在同一会话中用户点击编辑2个问题,然后代替覆盖以前的点击事件处理程序,而是导致2个事件处理程序运行,可能调用 saveQuestion 1),另一个可能调用 saveQuestion(2)。通过这样做1个问题覆盖了另一个。



有没有办法删除所有以前的点击

您可以使用 off()删除如下所示的事件:

  $ saveBtn)。off(click); 

但这会移除与此元素绑定的所有点击事件。如果带有SaveQuestion的函数是唯一的事件绑定,那么上面的函数就会这样做。如果没有执行以下操作:

  $(#saveBtn {saveQuestion(id);}); 


I'm having a problem. Basically, when a user clicks an 'Edit' link on a page, the following Jquery code runs:

$("#saveBtn").click(function () {
    saveQuestion(id);
});

By doing this, the onClick event of the save button calls the saveQuestion() method and passes on the ID of the question for which the 'Edit' link was clicked.

But if in the same session the user clicks edit on 2 questions, then instead of overwriting the previous click event handler, it instead causes 2 event handlers to run, one which might call saveQuestion(1) and the other might call saveQuestion(2). By doing this 1 question overwrites the other.

Is there a way to remove all previous click events that have been assigned to a button?

解决方案

You would use off() to remove an event like so:

$("#saveBtn").off("click");

but this will remove all click events bound to this element. If the function with SaveQuestion is the only event bound then the above will do it. If not do the following:

$("#saveBtn").off("click").click(function() { saveQuestion(id); });

这篇关于如何清除Jquery中的所有Click事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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