Jquery appending without removing

2019-06-16 11:51发布

问题:

So I need to grab content from a specific class and put it in a div, which I use append for...my issue is that append removes the item I append, and I need it to stay there, Here is my code:

$(document).ready(function(){
    var $content = $('#popupcontent');
    var $window = $('#popupwindow');
    $('.open').click(function(){
        //alert('runnning');
        var a = $(this).contents('span');
        $content.append(a);
        $window.fadeIn(300);
    });
    $('.close').click(function(){
        //alert('running');
            var a = $content.contents('span');
        $window.fadeOut(300);
        $('#popupcontent span').remove();
    });
});

So how can I get the content, when clicked, from each .open span to the #popupcontents id without removing it from the .open class?

To show you what I mean: JSFIDDLE

NOTE: the second time you click a link, it wont append any content because that content has been removed from that class, which is not what I want

NOTE2: I cannot simply just append instead of remove in the $('.close').click function because I cannot detect which instance of the .open class the content came from.

回答1:

You need to clone the element and append the clone:

$('.open').click(function(){
    //alert('runnning');
    var a = $(this).contents('span');
    $content.append(a.clone());
    $window.fadeIn(300);
});

Demo