jQuery .remove() call in callback triggers infinite loop

房东的猫 提交于 2019-12-08 19:45:31

You should have checked your browsers error console instead of just relying on the blackbirdjs console.

Then you would have noticed that the browsers error console is flooded with error messages too (with either of your code versions)

The actual problem in your code is

this.remove();

this is a HTML DOM element in the callback-function and doesn't have the function remove() thus the children only get hidden but not really deleted. And on this.remove() you get an exception. As the callback-function throws an exception jQuery ends up in an endless loop trying to do its job

What you need to do is wrapping the element in a jQuery object.

$(this).remove();

Now it's also clear why the second version seems to have fixed the error

log.info("Removing feedback div..."); //error logged
this.remove();  //exception

this.remove();  //exception
//log line not executed as previous line threw exception
log.info("Removing feedback div...");

The fact that jQuery even ends up in and endless loop and if this is correct behavior is debatable and needs more investigation deeper in the inner-workings of jQuery. But this isn't of interest to you

For those interested there is realted bug ticket

http://dev.jquery.com/ticket/2846

I have seen an issue just like this but in a different context; however, I suspect the root cause is the same.

If you take a look at log.info, you'll see that it inserts a node into the DOM. If one of the jquery functions happens to be traversing the DOM in just the right location, in particular, right at the spot where log.info is inserting the node, and then if that causes your callback to be invoked, your callback will insert another node, and you end up in an infinite loop.

The question of why this doesn't happen in IE8 is likely to be one of two reasons: either the DOM structure isn't exactly the same across browsers, or IE8 uses a different strategy for handling DOM node insertion while javascript code is traversing the tree.

You might try using Firebug, placing a breakpoints around the problematic lines and then viewing the DOM tree to see if you can spot behavior like this.

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