如何在使用 jquery 克隆时获取当前数据

How to get current data while cloning using jquery

如何在使用 jquery 克隆时获取元素的当前数据。克隆时,它只是复制元素中的默认数据。

这是代码

    souRce.clone()
    .prop('id', newName)    
    .html(function () {
        return $(this).html().replace(RegExp(PrevID, 'g'), newName); 
    })                                                  
    .appendTo(DestiNation);

问题是,您没有使用克隆元素,而是使用原始 html 更改其内容,这将用原始 html 标记

替换运行时内容

因此,与其替换整个 html,不如更新 idname 属性,例如

var counter = 1;

function clone() {
  var souRce = $('.item').eq(0),
    DestiNation = $('#ct'),
    PrevID = 'item-' + counter,
    newName = 'item-' + ++counter;

  var regex = RegExp(PrevID, 'g');
  souRce.clone()
    .prop('id', newName)
    .find('[id], [name]').each(function() {
      if (this.id) {
        this.id = this.id.replace(regex, newName);
      }
      if (this.name) {
        this.name = this.name.replace(regex, newName);
      }
    }).end()
    .appendTo(DestiNation);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ct">
  <div class="item" id="item-1">
    <input name="a" value="A" id="a-item-1" />
    <input name="b" value="B" id="b-item-1" />
    <input name="c-item-1" value="C" id="c-item-1" />
  </div>
</div>
<button onclick="clone()">Clone</button>