2015-12-16 28 views
1

所以,我有以下PHP值:jQuery的克隆具有不同PHP數組值

PHP:

<?php 
$data = array("Mike","Sean","Steve"); 
?> 

<script type="text/javascript"> 
    var tag_data = <?php echo json_encode($data); ?>; 
</script> 

<div class="container"> 
    <div class="content"> 
     <p></p> 
    </div> 
</div> 

JS:

????

所以,我試圖在<p>中使用第一個值(邁克),然後重複整個事情來顯示第二個值如下,同時保留以前生成的容器。

<div class="container"> 
    <div class="content"> 
     <p>Mike</p> 
    </div> 
</div> 
<div class="container"> 
    <div class="content"> 
     <p>Sean</p> 
    </div> 
</div> 
<div class="container"> 
    <div class="content"> 
     <p>Steve</p> 
    </div> 
</div> 

我才知道,我可以使用clone jQuery中重複格,但我不知道如何正確地做到這一點。

我想用隨後的數組值重複整個容器。

有人可以告訴我如何實現這個基本版本?

回答

2

這樣的事情應該可以做到!基本上,您需要更改元素,更改內容,將克隆插入到DOM中,然後刪除模板。請記住將該JavaScript放在模板之後,或者使用jQuery文檔就緒功能。

var tag_data = ["Mike","Sean","Steve"]; // <?php echo json_encode($data); ?>; 
 

 
// Get the template element, you will probably want to use a more-specific selector. 
 
var $containerTemplate = $('.container'); 
 
// Itterate over your array. 
 
tag_data.forEach(function(person) { 
 
    // CLone the template element. 
 
    var $cloned = $containerTemplate.clone(); 
 
    // Set the text from the array. 
 
    $cloned.find('p').text(person); 
 
    // Insert in order where the template elements comes from. 
 
    $cloned.insertBefore($containerTemplate); 
 
}); 
 
// Remove the template element. 
 
$containerTemplate.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 

 
<div class="container"> 
 
    <div class="content"> 
 
     <p></p> 
 
    </div> 
 
</div>

+0

這正是我需要的! =)謝謝!學習新東西! =) –