简体   繁体   English

带有回调的jQuery克隆功能-无法按预期工作

[英]jQuery Clone function with callback - not working as expected

First, here is a JSfiddle with my work: http://jsfiddle.net/xzGxR/ 首先,这是我工作的JSfiddle: http : //jsfiddle.net/xzGxR/

The JavaScript: 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: 和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. 这样做的目的是使用HTML并创建它的副本-然后用javascript对象中的数据填充这些副本。 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 试试这个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);
});​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM