最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I remove a specific event callback from an HTML element with jquery? - Stack Overflow

programmeradmin3浏览0评论

I have an element in a webpage which has several callbacks on it

// First callback
$("#element").click(fn1);

// Second callback
$("#element").click(fn2);

// Definitions
function fn1(){console.log("1");}
function fn2(){console.log("2");}

Is there a way to remove only fn2 from the list of callbacks triggered by jQuery. I know I could add an 'if' inside the function and some global variable, but that's not what I'm looking for.

I have an element in a webpage which has several callbacks on it

// First callback
$("#element").click(fn1);

// Second callback
$("#element").click(fn2);

// Definitions
function fn1(){console.log("1");}
function fn2(){console.log("2");}

Is there a way to remove only fn2 from the list of callbacks triggered by jQuery. I know I could add an 'if' inside the function and some global variable, but that's not what I'm looking for.

Share Improve this question asked Mar 12, 2013 at 9:31 malbermalber 1,0734 gold badges16 silver badges24 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

The second parameter in the unbind function specifies the handler to unbind.

$("#element").unbind("click", fn2);

Working Example: http://jsfiddle/k73Nx/

Interesting that nobody mentioned namespaces yet. Is there a reason for that?

When attaching your event, you can namespace it. Instead of $(elem).on('click', fn) you would add a namespace to the click event. $(elem).on('click.namespaced', fn)

When unbindung, you can then unbind that exact event, using the namespace as well. $(elem).off('click.namespaced')

This is most practical when you're defining your event function inline.

One more thing you can do with namespaces is to unbind all event types within a namespae with just a single call: $(elem).off('.namespaced')

Be careful with your syntax here, other answers are very loose with theirs.

If you use:

$('#element').on('click',function() {
 //callback code
});

Then you must use:

$('#element').off('click');

You cannot use

$('body').off('click','#element',function() { }); 

or

$(document).off('click','#element',function() { }); 

because you originally bound your event to #element, not to document or body.

Use unbind: http://api.jquery./unbind/

Example:

$(document).unbind('click', fn2);

use .off

 $("#element").off("click",fn2);

working fiddle

发布评论

评论列表(0)

  1. 暂无评论