2014-01-19 62 views
0

我試圖複製動態創建的單個div。我正在使用來自this question的javascript,它可以起到一定的作用。但是,用戶應該能夠複製任何動態創建的div。不幸的是,目前只有最後一個div被複制,無論點擊哪個按鈕。複製動態創建的div

這裏是我的代碼...

 <?php $ii=0; //set counter 

      foreach($bin_question_data as $k=>$v){ //loop through each section to create div ?> 

       <div id="duplicater<?php echo $ii;//use counter to create individual div id ?>"> 

        <h4><?php echo $v[0]['bintype'];?></h4> 

      <?php foreach($v as $vv){ //loop through section elements to display questions?> 

          <?php echo $bin_question=$vv['binquestiontext']; 
           $questionid=$vv['binquestionid'];?> 


        <!--questions are dynamically created here-->  

      } //end loop through section questions ?> 

       </div><!-- end div to be duplicated--> 

        <!--Add button to duplicate preceding div--> 

     <p><input type="button" name="add_bin" 
     id="add_bin<?php echo $ii;?>" onlick="duplicate()" value="Add <?php echo $v[0]['bintype'];?> bin" /></p> 

       <!--script to carry out duplication--> 

      <script type="text/javascript"> 

      document.getElementById('add_bin<?php echo $ii;?>').onclick = duplicate; 


      var i = 0; 
      var original = document.getElementById('duplicater<?php echo $ii;?>'); 


       function duplicate() { 
        var clone = original.cloneNode(true); // "deep" clone 
        clone.id = "duplicetor" + ++i; // there can only be one element with an ID 
        original.parentNode.appendChild(clone); 
       } 
      </script> 



    <?php $ii++; //increase counter 

    }//end original section loop ?>   

任何提示,以我要去錯了還是什麼我已經錯過了會受到歡迎,其中!

非常感謝您的幫助。

回答

0

你重新創建的這個代碼塊,每div的你做:

<script type="text/javascript"> 

document.getElementById('add_bin<?php echo $ii;?>').onclick = duplicate; 


var i = 0; 
var original = document.getElementById('duplicater<?php echo $ii;?>'); 


function duplicate() { 
    var clone = original.cloneNode(true); // "deep" clone 
    clone.id = "duplicetor" + ++i; // there can only be one element with an ID 
    original.parentNode.appendChild(clone); 
} 
</script> 

也許你需要的是這樣的一個重複的()函數:

}//end original section loop ?> 
<script> 
function duplicate(index) { 
    var original = document.getElementById('duplicater' + index); 
    var clone = original.cloneNode(true); // "deep" clone 
    clone.id = "duplicetor" + original.parentNode.childNodes.length; 
    original.parentNode.appendChild(clone); 
} 
</script> 

並確保通過參數複製():

<input type="button" name="add_bin" 
    id="add_bin<?php echo $ii;?>" onlick="duplicate(<?php echo $ii;?>)" ... 

編輯:我改變了如何設置duplicateetor id,因爲它不會工作,否則

+0

感謝您的快速回復@MazeHatter,不幸的是它不會複製任何東西.... –

+0

我的意思是PHP foreach循環放在