簡體   English   中英

在第二次單擊jQuery上刪除附加元素

[英]Remove Appended Element on Second Click jQuery

當您單擊灰色心臟時, div會附加到右側的容器中。 當您單擊粉紅色的心時,我希望它刪除附加的元素。 它只是不斷追加內容...

$('.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
        }

});

這是小提琴

似乎應該有更簡便的方法,從瀏覽器檢查返回的顏色絕不是一個好主意,因為它不是很一致。

而是添加一個類

.pink {
    color: #EA4C88;
}

然后做

$('.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');
});

小提琴

嘗試這個:

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
}

工作提琴: http : //jsfiddle.net/robertrozas/XDk6s/3/

您實際上並沒有抓住要刪除的元素,而是試圖刪除該元素的第二個副本,該副本未附加在任何地方。 要刪除該元素,您想在第二個列表中找到它,然后將其刪除。 因此,您的if語句的第二部分變為:

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

工作小提琴: http : //jsfiddle.net/XDk6s/7/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM