简体   繁体   中英

Cloned element can't be removed

I have a grid where if a user hovers over a box, a clone of that box is made and positioned directly over it (it's a z-index/overlay thing). When the user leaves that box with the cursor, an animation is supposed to play and at the end of it the box is removed().

The problem is that the animation completes but the clone isn't removed. I use console.logs and alerts to tell me if the animation completes and it alerts fine but anything to be done to that cloned client after animation completes doesn't go through. Here's an example:

clonedClient.slideUp(300, function(){
        alert('ya');
        clonedClient.remove();
});

After the slideUp completes, alert is triggered but remove isn't.

Here's a jsfiddle so you can see what's happening

http://jsfiddle.net/Q6fVP/1/

The mouseenter event is triggered twice (because the selected-client clone, also has a class of client . If you add console.log in the mouseenter event, you'll notice:

entering <div class=​"client">​hello​</div>​
entering <div class=​"client selected-client" style=​"background-color:​ red;​ position:​ absolute;​ top:​ 0.5em;​ background-position:​ initial initial;​ background-repeat:​ initial initial;​">​hello​</div>​

You'll want to omit the mouseenter event if the element that it is being triggered on is your selected-client .

ie in your first event handler:

if($this.hasClass('selected-client')){return;}

or, more completely, for that block of code:

$(document).on({
    mouseenter: function(){
        var $this = $(this);
        if($this.hasClass('selected-client')){
            return;
        }
        var clientClone = $this.clone().css({background:'red', position:'absolute', top: '0.5em'}).addClass('selected-client');
        clientClone.insertBefore(this);
    }
}, 'div.client');

You are using $(document).on() , which means the event handler is attached to document. When you cloned your <div> element, the class .client was also applied to the clone. And when you inserted the clone after the original, mouseenter was fired again, because you entered the newly cloned element (another clone was made here).

My solution is to remove .client class from the clone before inserting.

http://jsfiddle.net/Q6fVP/8/

If I understand correctly I think you want to replace clonedClient.remove();

with $('.selected-client').remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM