简体   繁体   中英

Remove Appended Element on Second Click jQuery

When you click the gray heart, the div gets appended to a container on the right side. I want it to remove the appended element when you click the pink heart. It just keeps appending the content...

$('.icon-heart').click(function(){
    var $newEl = $(this).closest('.color-container').html();

        if( $(this).css('color') === 'rgb(204, 204, 204)' ) { // if gray
            $(this).css('color', 'rgb(234, 76, 136)'); // turn to pink

            $('.b').append($newEl); // append new element


        } else if( $(this).css('color') === 'rgb(234, 76, 136)' ) { // if pink
            $(this).css('color', 'rgb(204, 204, 204)'); // turn to gray
            $newEl.remove(); // remove appended element
        }

});

Here is the Fiddle

Seems like there should be easier ways to do that, checking a returned color from the browser is never a very good idea, as it's not very consistent.

Instead, add a class

.pink {
    color: #EA4C88;
}

Then do

$('.icon-heart').click(function () {

    if ($(this).is('.pink')) {
        if ($(this).data('el')) $(this).data('el').remove();
    }else{
        var clone = $(this).closest('.color-container').clone();
        $('.b').append(clone);
        $(this).data('el', clone);
    }

    $(this).toggleClass('pink');
});

FIDDLE

Try this:

else if ($(this).css('color') === 'rgb(234, 76, 136)') { // if pink
    $(this).css('color', 'rgb(204, 204, 204)'); // turn to gray
    $('.b div').last().remove(); // remove appended element
}

Working fiddle: http://jsfiddle.net/robertrozas/XDk6s/3/

You aren't actually grabbing the element you need to remove - you're trying to remove a second copy of the element that hasn't been attached anywhere. To remove the element, you want to find it in your second list, then remove it. So the second part of your if statement becomes this:

else if ($(this).css('color') === 'rgb(234, 76, 136)') { // if pink
    $(this).css('color', 'rgb(204, 204, 204)'); // turn to gray
    $('.b').find(".color-block[data-color='" + $(this).closest(".color-block").data("color") + "']").remove();
}

Working Fiddle: http://jsfiddle.net/XDk6s/7/

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