2012-06-01 25 views
1

首先不能正常工作,這裏是我的工作的jsfiddle:http://jsfiddle.net/xzGxR/有回調jQuery的克隆功能 - 如預期

中的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>​ 

克隆的代碼有問題,但我無法弄清楚什麼。任何建議/幫助真的很感激。

回答

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

謝謝謝謝謝謝。我只是想要一些建議,但你解決了我的問題。神奇 – TaylorMac

+0

沒問題。我很確定這個錯誤發生了,因爲你在克隆這個項目並將它插入到dom中,然後再對它進行更改,但是直到我玩了它之前我都沒有確定:) –