目前,我正在try 用数组中相同的值替换子元素

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功能运行良好,符合预期

推荐答案

JavaScript对象是引用.这意味着整个程序的内存中只有一个h.element,因此,如果您告诉DOM用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/

Javascript相关问答推荐

在Angular中将样式应用于innerHTML

InDesign—创建一个独立的窗口,在文档中进行更正时保持打开状态

如何找出摆线表面上y与x相交的地方?

Mongoose post hook在使用await保存时不返回Postman响应

v—自动完成不显示 Select 列表中的所有项目

我的角模板订阅后不刷新'

可更改语言的搜索栏

如何在coCos2d-x中更正此错误

如何强制Sphinx中的自定义js/css文件始终加载更改而不缓存?

为什么123[';toString';].long返回1?

在HTML语言中调用外部JavaScript文件中的函数

使用getBorbingClientRect()更改绝对元素位置

我想将Sitecore搜索面过滤器从多个转换为单个

将相关数据组合到两个不同的数组中

如果NetSuite中为空,则限制筛选

如何将字符串拆分成单词并跟踪每个单词的索引(在原始字符串中)?

更新文本区域行号

在JS/TS中构造RSA公钥

已在EventListener中更新/更改异步的React.js状态对象,但不会导致组件重新呈现

我正在为我的单选按钮在HTML中设置一个值.使用Java脚本,我如何才能获得该值?