Will jquery empty() method clear the event listene

2019-04-20 21:05发布

I have an element with a lot of child elements. I want to clear the content of this element and replace it with new structure.

The child elements are assigned with various event listeners and not all of those listeners are created through jquery bind method.

If I use jquery's empty method to clear the element will it remove all the event listeners or will it clear only the listeners created through jquery bind method?

3条回答
戒情不戒烟
2楼-- · 2019-04-20 21:23

As several commenters have mentioned, the jQuery docs say that empty() does indeed remove event handlers: http://api.jquery.com/empty/

Perhaps that wasn't the case when this question was posted, but this page is the first hit on Google.

查看更多
狗以群分
3楼-- · 2019-04-20 21:27

You can unbind all listeners of a object with the .unbind() and leave the params empty

If you want to remove all the children of an element. just user $("#parent").children().remove();

With the live() and die() methods you can add eventhandlers to elements which do not yet exists yet. with $(".element").live("click", function(){}) adds a function to all .element objects that are currently in your HTML or those who are added in the future.

查看更多
甜甜的少女心
4楼-- · 2019-04-20 21:31

it will not clear the event listeners. But you should use this event listeners as live() event, because, you are changing DOM elements dynamically.

for e.g:

$('a').live('click', function(){
   // your stuff
});

// jQuery 1.7 required for following code snippet

$(document).on('click', 'a', function(){
   // your stuff
});
查看更多
登录 后发表回答