【问题标题】:To generate a cloned div with html controls , dynamic ID and listeners for the elements in DIV为 DIV 中的元素生成带有 html 控件、动态 ID 和侦听器的克隆 div
【发布时间】:2013-05-22 00:25:40
【问题描述】:

我想复制一个 div 及其所有内容,以生成一个克隆的 div(例如,动态地向发票添加行)。我需要克隆 div 的内容,包括 html 控件、动态 ID 和 DIV 中元素的侦听器!!

有没有简单的方法来做到这一点?谢谢!

代码有效,但它没有克隆整个 DIV 它还克隆文本框 ID 可以帮助我。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

<head>

<style>
body
{
    background: none !important;
}
</style>

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

    <title>      Dynamically create input fields- jQuery </title>


    <link href="theme/css/ui/ui.base.css" rel="stylesheet" media="all" />

    <link href="theme/css/themes/black_rose/ui.css" rel="stylesheet" title="style" media="all" />



    <!--[if IE 6]>

    <link href="theme/css/ie6.css" rel="stylesheet" media="all" />



    <script src="theme/js/pngfix.js"></script>

    <script>

      /* Fix IE6 Transparent PNG */

      DD_belatedPNG.fix('.logo, ul#dashboard-buttons li a, .response-msg, #search-bar input');



    </script>

    <![endif]-->

 <script  src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
    </script>
    <script type="text/javascript">
      $(function() {
          var i = 1;
        $('#addNew').live('click', function() {
            var getParentId = $(this).closest('fieldset').attr('id');
            var getParentId1 = $('#'+getParentId);
            i = $('#'+getParentId+' p  input').size();
          if( i > 6 ) {
            alert("Limitation upto 5");
            return false;
          }
          $('<p><input type="text" id="p_new" name="p_new_' + i +'" value="" placeholder="I am New" /><a href="#" id="remNew">Remove</a> </p>').appendTo(getParentId1);
          i++;
          return false;
        });

        $('#remNew').live('click', function() {
          if( i > 2 ) {
            $(this).parents('p').remove();
            i--;
          }
          return false;
        });

        // Duplicate Query Block
        var addQueryBlock = $('#queryblock');
        var j = $('#queryblockfld').size() + 1;
        $('#addNewQueryBlock').live('click', function() {
          if( j > 6 ) {
            alert("Limitation upto 5");
            return false;
          }
          $('<fieldset id="queryblock' + j +'" name="queryblock' + j +'"><legend>Query Block' + j + '</legend><div style="float:right;" id="addqueryblock"><a style="text-decoration: none;" href="#" id="remNewFieldset"> &#8211; </a><a style="text-decoration: none;" href="#" id="addNewQueryBlock">+</a></div><div id="addinput"><p><input type="text" id="p_new1" name="p_new" value="" placeholder="Input Value" /><a href="#" id="addNew">Add</a><input type="text" id="input2" name="input2" value="" placeholder="input2" /></p></div></fieldset>').appendTo(addQueryBlock);
          j++;
          return false;
        });

         $('#remNewFieldset').live('click', function() {
          if( j > 2 ) {
            $(this).parents('fieldset').remove();
          j--;
          }
          return false;
        });
      });
    </script>

</head>


  <body>
    <h2>
      Dynamically Add Another Input Box
    </h2>

    <div id="queryblock">
      <fieldset id="queryblockfld" name="queryblockfld">
        <legend>
          Query Block
        </legend>
        <div style="float:right;" id="addqueryblock">
          <a style="text-decoration: none;" href="#" id="addNewQueryBlock">+</a></div>
          <div id="addinput">
            <p>
              <input type="text" id="p_new3" name="p_new3" value="" placeholder="Input Value" />
              <a href="#" id="addNew"> Add </a> Wlcome to my world
              <input type="text" id="input2"  name="input2" value="" placeholder="input2" />
            </p>
          </div>
        </fieldset>
    </div>
      </body>
    </html>

【问题讨论】:

  • 简单使用jQuery.clone()方法:)
  • 但是 DIV 中的 Input 字段会被克隆到新名称吗?请检查以下 URL 我也尝试过 jsfiddle.net/kXmpY 但有点粘。
  • 好吧,如果您想附加动态 ID 和侦听器,那么您的问题是不正确的。您不是要克隆元素 :) 您想要的是能够创建具有某些参数的 HTML 元素。我认为你需要建立一个工厂...... :)
  • 我只是想办法做到这一点。我觉得我做了一些什么但不是完整的功能。

标签: javascript jquery html clone jquery-clone


【解决方案1】:

您可以使用 jQuery 的 .clone() 方法来实现。考虑以下代码:

//first clone your div
clonedDiv = $('#IdOfYourDIV').clone();

//use .attr() method to change the id
$(clonedDiv).attr('id','YourDynamicID');

现在您的“克隆” div 已准备就绪。但是使用第一个 div 的 ID 绑定的处理程序在 clonedDIV 上不起作用。

【讨论】:

    【解决方案2】:

    经过长时间的搜索,我找到了一个可以满足我要求的工作代码。请参考链接

    <div id="events_wrapper">
    <div id="sub_events">
    <p><label>Art Space </label>
    <input type="text" id="as_name" name="as_name" class="txt-input small"/>
    <input type="hidden" id="as_id" name="as_id" class="txt-input small"/>                                      
    </p>
    
    <p><label>Start Date </label>
    <input type="text" id="start_date" name="start_date" class="datepicker txt-input small"/>
    
    <label>End Date </label>
     <input type="text" id="end_date" name="end_date" class="datepicker txt-input small" />
    </p>
    
    <p><label>Opening Hours </label>
     From : <input style="width: 100px" type="text" id="time_from" name="time_from" class="timepicker txt-input small" />
    
    To : <input style="width: 100px" type="text" id="time_to" name="time_to" class="timepicker txt-input small"/> </p>                                                    
    </div>
         <br/>
    <input type="button" id="add_another_event" name="add_another_event" value="Add Another" />
    

    JS函数:

    $('#add_another_event').click(function() 
        {
            alert('test');var $address = $('#sub_events');
            var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
            var newNum = num + 1;
            var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
    
            //set all div id's and the input id's
            newElem.children('div').each (function (i) {
                this.id = 'input' + (newNum*5 + i);
            });
    
            newElem.find('input').each (function () {
                this.id = this.id + newNum;
                this.name = this.name + newNum;
            });
    
            if (num > 0) {
                $('.clonedAddress:last').after(newElem);
            } else {
                $address.after(newElem);
            }
    
            $('.datepicker', newElem).removeClass('hasDatepicker').datepicker();
            $('#btnDel').removeAttr('enabled'); 
        });       
    
    $('.datepicker').datepicker();                            
    

    Also ReferJquery date picker and time picker do not work when fields are dynamically created

    希望这对某人有所帮助。!

    上述代码的工作示例:http://jsfiddle.net/MkhZ2/24/

    【讨论】:

      【解决方案3】:

      我是这样的开发者,所以我的解决方案非常简单。假设div 包含在body 中,则使用克隆复制您的divappentTo 集。

      $("#btn_act").click(function(){
         var body = $("body"); //Where is contained the object
         var obj = $("#myDiv"); //Object who will be cloned
         var e = obj.clone(true).appendTo(body);
         $(e).find("input").each(function(){
             //ie: myInput0, myInput1 will be deleted
             if ($(this).attr("id") != 'myInput'){
                $(this).remove();
             }
         });
      });
      

      如果您仍然需要一个小型解决方案,请认为这会对您有所帮助。

      【讨论】:

        【解决方案4】:
        function duplicate() {
            var original = document.getElementById('duplicater' + i);
            var clone = original.cloneNode(true); // "deep" clone
            clone.id = "duplicetor" + ++i; // there can only be one element with an ID
            clone.onclick = duplicate; // event handlers are not cloned
            original.parentNode.appendChild(clone);
        }
        

        不是duplicetor而是duplicater :) 那么它不会在控制台中显示错误并添加一个克隆的div

        为什么不克隆输入字段?它会克隆它...

        【讨论】:

        • Div 是单独的,而不是 DIV 中元素的 ID。
        • ins't 'duplicater' div's ID 不是里面的元素?还是我不明白?
        • DIV id 更新为新的Id,但Input 字段的Id 没有更新为新名称?
        猜你喜欢
        • 1970-01-01
        • 2012-05-19
        • 1970-01-01
        • 2016-12-04
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        • 1970-01-01
        • 2011-04-29
        相关资源
        最近更新 更多