简体   繁体   中英

jQuery Clone function with callback - not working as expected

First, here is a JSfiddle with my work: http://jsfiddle.net/xzGxR/

The JavaScript:

function dataClonePrototype(JSOtarget, ElementPrototype, callback) {
    for (i = 0; i < JSOtarget.length; i++) {
        var TargetElement;
        if (!Eclone) { // Only create it on first interval
            TargetElement = $(ElementPrototype);
            var Eclone = TargetElement.clone(); // We only want to create a copy of this clone...
        } else {
            TargetElement = Eclone.clone().insertAfter(ElementPrototype);
        }
        callback(TargetElement, JSOtarget[i]);
    }
}

var returnedJSO = 
{
    "Animals": [
        {
            "Title": "Dogs",
            "Amount": 300
        },
        {
            "Title": "Pigs",
            "Amount": 230
        },
        {
            "Title": "Cats",
            "Amount": 340
        }
    ]
}

dataClonePrototype(returnedJSO.Animals, "section#animals", function(Element, JSOtargetAtKey) {
    Element.children("header").html(JSOtargetAtKey.Title);
    Element.children("article").html(JSOtargetAtKey.Amount);
});​

And the HTML:

<section id="animals">
     <header></header>
     <article></article>
</section>​

The output should (visually) look like this:

Dogs
300
Pigs
230
Cats
340

Yet, it looks like this.

Dogs
300
Cats
340
Pigs
230
Cats
340

The goal of this is to use the HTML and create clones of it - then populate these clones with data from the javascript object. It should populate like this:

<section id="animals">
   <header>Dogs</header>
   <article>300</article>
</section>​

Something is wrong with the code that clones, but I can't figure out what. Any advice/help is really appreciated.

Try this jsFiddle

function dataClonePrototype(JSOtarget, ElementPrototype, callback) {

    $TargetElement = $(ElementPrototype);
    for (i = 0; i < JSOtarget.length; i++) {

        var $Eclone = $TargetElement.clone(); // We only want to create a copy of this clone...

        callback($Eclone, JSOtarget[i], $TargetElement);
    }
}


dataClonePrototype(returnedJSO.Animals, "section#animals", function($Element, JSOtargetAtKey, $Prototype) {
    $Element.children("header").html(JSOtargetAtKey.Title);
    $Element.children("article").html(JSOtargetAtKey.Amount)
        $Element.insertAfter($Prototype);
});​

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