Search code examples
jqueryclone

jQuery/JavaScript: Cloning with dynamic added content


I have a site here where the user can click on some divs. Then I add an "X" to it using this code:

function addEx( elem, insertClass ) {
        var element = $( elem );
        var newInsertClass = insertClass.replace('.', '');
        var insert = "<span class='" + newInsertClass + "'> X </span>";

        element.click(function(){
            var $this = $(this);

            if( $this.text().indexOf( "X" ) >= 0 ) {
                var id = $this.attr( "id" );
                $( "#" + id + " " + insertClass ).remove();
            } else {
                $this.append( insert );
            }   
        })
    }

As you can see, if the "X" is already there, I remove it. If it's not there, I add it. This works fine.

The user can also click on a "get results" button. The divs the user has clicked are then compared with the right answers. According to this, I add classes to the divs that were clicked correctly, too much or that were forgotten to click. This also works, but the content (the "X") gets lost. So I can see the CSS-stlying I supplied for these classes, but the "X" inside the div is missing after replacing the original with the clone. For adding the classes I use this code:

var test = $(".test");
var clone = test.clone(true,true);


function correction() {
    clone.children().filter(function() {
        return $.inArray('#' + this.id, forgotten) != -1;
    }).addClass("forgotten").end().filter(function() {
         return $.inArray('#' + this.id, toomuch) != -1;
    }).addClass("toomuch").end().filter(function() {
         return $.inArray('#' + this.id, correct) != -1;
    }).addClass("right");

   test.replaceWith(clone);                   
 }

I clone the element here, then add the appropriate classes on the clone and replace the original with the clone.

So my question is: How can I prevent this loss of content? I guess it's because the "X" are added dynamically? Or I also have more then one element with .test - could this be the cause?


Solution

  • The John Resig has answered a question about cloning objects using jQuery. It might help you