开发者

How to correctly use jQuery remove in this case

开发者 https://www.devze.com 2023-03-11 21:25 出处:网络
I have the following fiddle http://jsfiddle.net/ycysD/1/ in which i try to remove an element of 开发者_运维技巧the DOM using a funcion, also I have two events that execute this function, both do the s

I have the following fiddle http://jsfiddle.net/ycysD/1/ in which i try to remove an element of 开发者_运维技巧the DOM using a funcion, also I have two events that execute this function, both do the same thing however in one casi it fails

Sorry for the english and tell me if you need some other information


No idea if this is the correct behavior, but here's what I changed:

function closeMediaList(what){
    $('.media-list-display').fadeOut(function(){
        what.remove();
    });
};

what is the object which gets removed, so instead of just calling:

closeMedialList();

You call:

closeMediaList($(this));

Here's a demo of what the changes did: http://jsfiddle.net/t4u33/


The behavior is caused by a conflict in the code. When the close button is clicked you both create and remove a new .media-list-display.

 _close.bind('click',function(e){
//This line removes the .media-list-display div when 
//the close button is clicked

$('.media-list a').live('click',function(e){
//This line adds a new .media-list-display div when any `<a>` 
//inside .media-list is clicked.

The problem is that the close button is also an <a> inside .media-list so when it is clicked it triggers both events creating an endless loop of removing and creating.

Check this link out with alerts on the conflicting parts.

0

精彩评论

暂无评论...
验证码 换一张
取 消