【问题标题】:jQuery Clone function with callback - not working as expected带有回调的 jQuery 克隆函数 - 未按预期工作
【发布时间】:2012-06-01 22:53:35
【问题描述】:

首先,这是我工作的 JSfiddle:http://jsfiddle.net/xzGxR/

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

还有 HTML:

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

输出应该(视觉上)如下所示:

Dogs
300
Pigs
230
Cats
340

然而,它看起来像这样。

Dogs
300
Cats
340
Pigs
230
Cats
340

这样做的目的是使用 HTML 并创建它的克隆 - 然后用来自 javascript 对象的数据填充这些克隆。它应该像这样填充:

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

克隆的代码有问题,但我不知道是什么问题。非常感谢任何建议/帮助。

【问题讨论】:

    标签: javascript jquery html clone


    【解决方案1】:

    试试这个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);
    });​
    

    【讨论】:

    • 谢谢谢谢谢谢。我只是想要一些建议,但你解决了我的问题。太棒了
    • 没问题。我很确定错误正在发生,因为您在对其进行更改之前克隆了该项目并将其插入到 dom 中,但直到我使用它之前我才确定 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 2012-09-09
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多