innerHTML修改整个数组 [英] innerHTML modifying whole array

查看:129
本文介绍了innerHTML修改整个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Javascript代码出现了意外的行为。我用 document.createElement( tr)单元格数组创建的一行代码,其代码为:
cellule = new Array(3).fill(document.createElement( td));

I have got an unexpected behavior from my Javascript code. I'm creating a line of table with document.createElement("tr") and an array of cells with that code: cellule = new Array(3).fill(document.createElement("td"));

但是当我使用 innerHTML 属性(视情况而定)填充我的值,整个数组都被修改了。这是完整的代码:

But when I'm filling it with my values using innerHTML property case by case, the whole array is modified. Here is full code:

ligne = document.createElement("tr");;
cellule = new Array(3).fill(document.createElement("td"));

cellule[0].innerHTML = "Chat";
cellule[1].innerHTML = "Chien";
cellule[2].innerHTML = "Alligator";

ligne.appendChild(cellule[0]);
ligne.appendChild(cellule[1]);
ligne.appendChild(cellule[2]);
maTable.appendChild(ligne);

结果是:

cellule[0] => "Alligator"
cellule[1] => "Alligator"
cellule[2] => "Alligator"

为什么我的整个数组都填充了最后使用的innerHTML?

Why is my whole array filled with the last innerHTML used?

推荐答案

由于使用了'filll',因此复制了相同的td,从而导致了问题。一种方法是创建一个独立的td。

Because 'filll' was used, the same td was copied, causing an issue. One way is to create an independent td.

ligne = document.createElement("tr");
var datas = ['Chat', 'Chien', 'Alligator'];
for(var i=0; i<datas.length; i++) {
    var td = document.createElement("td");
    td.innerHTML = datas[i];
    ligne.appendChild(td);
}

maTable.appendChild(ligne);

这篇关于innerHTML修改整个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆