根据ID将HTML表单的克隆附加到文档正文



我有一个html表单,当签名时,我想创建的多个副本一个接一个地直接显示。我糟糕的克隆功能是这样的:

function formCloner(numCopies) {
let cloneContainer = document.createElement("div");
cloneContainer.id = "formCopies";
for(i = 0; i < numCopies) {
// grab the whole html form
let html = document.getElementsByTagName("html")[0]; 
let htmlClone = html.cloneNode(true);
/*
* do some other stuff to the clone
*/
cloneContainer.appendChild(htmlClone);
}
document.body.appendChild(cloneContainer);
}

这种方法的一个大问题是,最终复制的所有表单元素都共享相同的ID。这很糟糕。我考虑过运行每个子节点并手动更改ID,但这似乎有些过头了。必须有一个更简单的答案,有人能推荐一种无痛的方法来实现将表单副本附加到文档主体的最终结果吗?

这很容易。。。简单地将所有具有ID的元素作为目标,并向它们添加_#。对for属性也要执行同样的操作,因为它们是您首先想要使用ID的唯一真正原因。

htmlClone.querySelectorAll("[id]").forEach(elem=>elem.setAttribute('id',elem.getAttribute('id')+"_"+i));
htmlClone.querySelectorAll("[for]").forEach(elem=>elem.setAttribute('for',elem.getAttribute('for')+"_"+i));

最新更新