我正在尝试创建“div”元素并尝试使用 Javascript 更改其内部 HTML,但它不会更改数组的特定元素,而是更改所有元素的 HTML 代码。
let bs_length = 2;
const bs_divs = new Array(bs_length).fill(document.createElement("div"));
bs_divs[0].innerHTML = "Hi";
console.log(bs_divs[0].innerHTML); // Hi
console.log(bs_divs[1].innerHTML); // Hi
如何更改此代码,使其仅更改第一个元素的 HTML?
最佳答案
When fill gets passed an object, it will copy the reference and fill the array with references to that object.
使用Array.from()
Array.from({length:bs_length}, () => document.createElement("div"));
关于Javascript 更改所有数组元素的 HTML 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54485366/