How to remove all Click event handlers in Jquery

試著忘記壹切 提交于 2019-11-26 12:57:23

问题


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?


回答1:


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); });



回答2:


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

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



回答3:


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



回答4:


If you used...

$(function(){
    function myFunc() {
        // ... do something ...
    };
    $('#saveBtn').click(myFunc);
});

... then it will be easier to unbind later.




回答5:


$('#saveBtn').off('click').on('click',function(){
   saveQuestion(id)
});

Use jquery's off and on



来源:https://stackoverflow.com/questions/825112/how-to-remove-all-click-event-handlers-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!