复制动态创建的div

时间:2014-01-19 10:05:11

标签: javascript

我正在尝试复制动态创建的各个div。我正在使用来自this question的javascript,这是一种享受。但是,用户应该能够复制任何动态创建的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 ?>         

我会非常感激地收到任何关于我出错或错过的提示!

非常感谢您的帮助。

1 个答案:

答案 0 :(得分: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>

然后确保将参数传递给duplicate():

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

编辑:我更改了duplicetor id的设置方式,因为它不会起作用