Will jquery empty() method clear the event listeners created through non jquery means

核能气质少年 提交于 2019-12-22 03:24:57

问题


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?


回答1:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/8120441/will-jquery-empty-method-clear-the-event-listeners-created-through-non-jquery

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