首页 > 解决方案 > 如何在或更快地克隆元素时重置 id 和 data-attr

问题描述

我想克隆这个 div:

<div id="parentdiv">
  <div id="child1" data-whatelse="123">Child Text</div>
  <div id="child2" data-whatelse="123">Child Text
  <div id="chilfofchild" data-whatelse="123">Child of Child Text</div>
</div>

所以我克隆它并将 id 重置为新的。

$('#parentdiv')
.clone()
.attr('id', my_new_id_for_cloned_div ).
insertAfter('#parentdiv'); 

如何重置克隆 div 内的所有 id 和 data-attributes?

标签: jqueryhtml

解决方案


我只需要自己做这件事。使用函数发送克隆对象和新 ID,并返回更新后的克隆对象。

//your parent function
var parentClone = $('#parentdiv').clone(true, true);

updateId(parentClone, your-new-id)
parentClone.insertAfter('#parentDiv');

//function to update the IDs
function updateId(theClone, newId) {
        $(theClone).find("[id]").add(theClone).each(function() {
            this.id = this.id.replace('key-to-update', newId);
        })
    }

我试图让函数的最后一行足够清晰,让任何人都能理解:基本上它读取“将克隆的 id 设置为当前 id,但用新的替换此字符串中的某些内容(key-to-update) id。我使用了“x”(我的克隆对象是隐藏的;如果您的对象是可见的并且称为“parentDiv”,那么您可以将“Div”替换为数字或时间戳(我将“x”替换为时间戳。)


推荐阅读