克隆div并遍历内部

时间:2017-09-12 19:39:29

标签: javascript jquery

我有一个带有输入的div,我希望在点击时使用不同的id克隆这个div,并且我希望其中的输入的id也改变,我想限制克隆的数量,< / p>

var div = document.getElementById('clonedDiv'),
clone = div.cloneNode(true); 
clone.id = "some_id";
document.body.appendChild(clone);
<div id="clonedDiv">
<p>Clone this div</p>
<input type="file" id="clonedInput">
</div>
<br>
<button type="button">Clone me</button>

我该怎么做?这是我的代码:

4 个答案:

答案 0 :(得分:1)

我想为您的问题提供原生的JS解决方案。它非常简单,适用于所有现代浏览器。

  • outerHTML是IE4 +,请参阅here
  • insertAdjacentHTML是IE4 +,请参阅here

&#13;
&#13;
const
  sourceDiv = document.getElementById('clonedDiv'),
  cloneTrigger  = document.getElementById('make-clone'),
  maxClones = 3;
  
let
  clonesCreated = 0;
  
function makeClone() {
  // Make sure there aren't too many clones created.
  if (clonesCreated === maxClones) {
    console.log('max clones reached');
    return;
  }
  
  let
    // outerHTML is llke innerHTML but includes the element itself.
    clone = sourceDiv.outerHTML;
      
  // Replace the two IDs for unique IDs    
  clone = clone.replace('clonedDiv', `clonedDiv_${clones}`);
  clone = clone.replace('clonedInput', `clonedInput_${clones}`);  
  
  // insertAdjacentHTML is like innerHTML except your can tell where it should be inserted in relation to the element. 
  // In this case, add the clone before the button element.
  cloneTrigger.insertAdjacentHTML('beforebegin', clone);
  
  // Increase the number of clones created.
  clonesCreated++;
}
  
cloneTrigger.addEventListener('click', makeClone);
&#13;
<div id="clonedDiv">
<p>Clone this div</p>
<input type="file" id="clonedInput">
</div>
<br>
<button id="make-clone" type="button">Clone me</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

由于您在问题中标记了jQuery,我们可以使用它来大大简化事情。

  1. 将单击事件处理程序绑定到克隆按钮,我们可以使用它来调用一个方法,比如clone(),它将处理所有克隆逻辑
  2. 定义一个全局变量,比如cloneCount,它存储已创建的克隆数,以便我们可以生成唯一ID
  3. 克隆您的目标<div>元素。
  4. 只需附加.add()
  5. ,即可修改目标元素及其子元素中的所有ID(使用cloneCount创建超集)
  6. 将克隆元素附加到DOM
  7. 如果要限制克隆数量,只需在方法中跟踪cloneCount即可。当它超过某个阈值时,返回退出该功能。

    这是一个概念验证示例:

    &#13;
    &#13;
    var $div = $('#clonedDiv');
        
    var cloneCount = 0,
        maxCloneCount = 5;
        
    var clone = function() {
    
      // Stop execution if we have cloned max number of times
      if (cloneCount >= maxCloneCount)
        return;
    
      // Construct clone
      var $clone = $div.clone();
      
      // Replace all IDs (of clone and its children) to make sure it is unique
      $clone.add($clone.children()).attr('id', function() {
        return this.id + '_' + cloneCount;
      });
      
      // Append to DOM
      $('body').append($clone);
      
      cloneCount++;
    };
    
    $('button').on('click', function(e) {
      e.preventDefault();
      clone();
    });
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="clonedDiv">
    <p>Clone this div</p>
    <input type="file" id="clonedInput">
    </div>
    <br>
    <button type="button">Clone me</button>
    &#13;
    &#13;
    &#13;

答案 2 :(得分:0)

要达到预期效果,请使用以下选项

var div = document.getElementById('clonedDiv');
var count = 0;
$('button').on('click',function(){
  if(count <= 3){
    $('#clonedDiv').clone().attr('id','cloneDiv'+count).appendTo('body');
  }

count++;


})

https://codepen.io/nagasai/pen/JrjNmq

使用计数变量
来限制数字克隆 使用ID属性和计数,可以将不同的ID分配给克隆的div - cloneDiv

答案 3 :(得分:0)

&#13;
&#13;
<!DOCTYPE html>
<html>

  <head>
    <script data-require="rxjs@4.0.6" data-semver="4.0.6" src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.6/rx.all.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    

    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div id = 'files'>
      
    </div>
    
    <br>
    <button type="button" id = 'clonebtn'>Clone me</button>
  </body>
<script type="text/javascript" charset="utf-8">
  // Code goes here

window.onload = init;

function init() {
 
  const observable = Rx.Observable.fromEvent($('#clonebtn'),'click');

  observable
  .take(4)
  .map(1)
  .scan((acc, curr) => acc + curr)
  .subscribe(i=>$('#files').before(getFileTemplate(i)));
  
}
function getFileTemplate(i){
  
  return `<div id='clonedDiv${i}'>
  <p>Clone this div${i}</p>
  <input type="file" id='clonedInput${i}'>
  </div>`;
}
</script>
</html>
&#13;
&#13;
&#13;