[英]How do I append cloned html elements to parent element on click using a loop?
The following piece of javascript is supposed to clone an HTML node, then append the clone to the originals' parent 50 times using a loop. 以下javascript应该克隆HTML节点,然后使用循环将克隆附加到原始父节点50次。
Right now, it only adds appends one clone per click. 现在,它只添加每次点击附加一个克隆。 the expected behavior is fifty clones appended at once.
预期的行为是一次附加五十个克隆。
CODE 码
// placeholder generators
document.querySelector(".dummy-load-home").addEventListener("click", gen)
function gen(){
const clone = document.querySelector('.card.featured').cloneNode(true);
let count = 0;
while(count < 50) {
document.querySelector('.card.featured').parentNode.appendChild(clone);
count++
}
}
Kindly draw to my attention what I have done wrong. 请注意我做错了什么。
That's because it's re-appending the same clone over and over again. 那是因为它一遍又一遍地重新附加同一个克隆。 So even though it does do it 50 times it doesn't look like anything is happening.
因此即使它确实做了50次,但看起来并没有发生任何事情。 You'd need to generate a new clone in the loop as well.
您还需要在循环中生成新的克隆。
function gen(){
const elementToClone = document.querySelector('.card.featured');
let count = 0;
while(count < 50) {
let clone = elementToClone.cloneNode(true);
document.querySelector('.card.featured').parentNode.appendChild(clone);
count++;
}
}
You could probably optimize it a bit more too by caching the parent node so you don't have to search for it every iteration of the loop - 您可以通过缓存父节点来更优化它,这样您就不必每次迭代循环都搜索它 -
function gen(){
const elementToClone = document.querySelector('.card.featured'),
parentNode = elementToClone.parentNode;
let count = 0;
while(count < 50) {
let clone = elementToClone.cloneNode(true);
parentNode.appendChild(clone);
count++;
}
}
And then maybe even better - creating a DocumentFragment and appending that at the very end so that less re-paints have to happen (although TBH I am not 100% on the performance gains of this one. Logically it seems like it must but I'm just doing a bit of research right now to confirm and so far haven't found anything conclusive) 然后甚至可能更好 - 创建一个DocumentFragment并在最后附加它以便减少重新绘制(虽然TBH我不是100%的性能增益这个。从逻辑上看它似乎必须但我'我现在正在做一些研究以确认,到目前为止还没有找到任何结论性的)
function gen(){
const elementToClone = document.querySelector('.card.featured'),
parentNode = elementToClone.parentNode,
fragment = new DocumentFragment();
let count = 0;
while(count < 50) {
let clone = elementToClone.cloneNode(true);
fragment.appendChild(clone);
count++;
}
parentNode.appendChild(fragment);
}
Use the following function: 使用以下功能:
function gen(){
let count = 0;
while(count < 50) {
const clone = document.querySelector('.card.featured:last-child').cloneNode(true);
document.querySelector('.card.featured').parentNode.appendChild(clone);
count++
}
}
Hope it works. 希望它有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.