element.replaceChildren() 函数是否使用重复值,或者是什么阻止了它的工作

Does element.replaceChildren() function work with duplicate values, or what is stopping this from working

目前我正在尝试替换数组中具有相同值的子元素
例如:

const e = document.createElement("div");
e.className = "e";
e.innerHtml = "test ";
const a = [e, e, e];
// test is appearing only once instead of multiple times
document.body.replaceChildren(...a);

我的代码是这样的:

    class MockElement {
        constructor(className, children = []) {
            this.element = document.createElement("div");
            this.className = className;
            this.children = children;
            this.element.className = className;
            console.log(Array(children))
            if (children) this.element.replaceChildren(...Array(children));
        };
        replaceChildren(c) {
            this.children = c;
            this.element.replaceChildren(...c);
        };
    };

    //const wrapper = document.getElementById("centirdle-boards");



    const fill = (c, t) => {
        // init new array
        let a = new Array();
        // loop through {t} times, adds new copy of {c} to the array each time
        for (let j = 0; j < t; j++) a.push( c );
        return a;
    };

    const h = new MockElement("h");
    // only seeing one of them
    document.body.replaceChildren(...fill(h.element, 5))

目前 fill 功能正常工作,符合预期
模拟元素 class 也可以正常工作

JavaScript objects 是引用。这意味着整个程序的内存中只有一个 h.element,因此如果您告诉 DOM 将 children 替换为 h.element 5 次,它只会插入一次,因为它是对单个元素的五个引用。

您必须创建多个元素。

对于您的代码示例,它看起来像这样:

// Calls `document.createElement` five times total
const elements = new Array(5)
  .fill(null)
  .map(() => new MockElement("h").element); 

document.body.replaceChildren(...elements);

查看这篇文章以了解更多信息:https://dmitripavlutin.com/value-vs-reference-javascript/