jquery - 如何在或更快地克隆元素时重置 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?
解决方案
我只需要自己做这件事。使用函数发送克隆对象和新 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”替换为时间戳。)
推荐阅读
- javascript - 带有firebase的JavaScript中的变量
- azure - 在突触池中重命名表和列以及传输模式
- javascript - 从 react-native-image-picker 中选择后不显示图像
- android - android Glide 资源已准备好但图像未显示
- javascript - UnhandledPromiseRejectionWarning: TypeError: object is not iterable... 当使用 await Promise.all(promises);
- postgresql - Postgres 的 Adventureworks 数据库
- unix - 在unix中将一列拆分为一行并提取选择性数据
- java - Spring注解/记录spring自定义事件的方法
- node.js - Azure - 持续运行 WebJob:支持 Node.JS 和文档
- angular - 角度无法将条纹导入组件