目前我正在嘗試替換陣列中具有相同值的子元素,
例如:
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功能作業正常,并且按預期
模擬元素類也作業正常
uj5u.com熱心網友回復:
JavaScript 物件是參考。這意味著整個程式的記憶體中只有一個h.element,所以如果你告訴 DOM 用h.element5 次替換 children,它只會插入一次,因為它是對單個元素的 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/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/467748.html
標籤:javascript html dom
上一篇:嘗試在JavaScript中列印資料陣列物件時出現未捕獲的錯誤
下一篇:如何在所有網站頁面中獲得Y位置
