创建具有多行和多列的 table

Creating a table with multiple rows and column

我想创建一个 4 行 3 列的 table,我正在这样做,但是使用这段代码我没有得到任何东西。我在这里做错了什么?

let cell = ["a","b","c","x"];
let cell1 = ["d","e","f","y"];
let cell2 = ["g","h","i","z"];

function myFunction() {
  var x = document.createElement("TABLE");
  x.setAttribute("id", "myTable");
  document.body.appendChild(x);
for(let i=0; i< 3; i++){
  var y = document.createElement("TR");
  y.setAttribute("id", myTr[i])
  document.getElementById("myTable").appendChild(y);
  var z = document.createElement("TD");
  var t = document.createTextNode(cell[i]);
  var z1 = document.createElement("TD");
  var s = document.createTextNode(cell1[i]);
  var z2 = document.createElement("TD");
  var r = document.createTextNode(cell2[i]);
  z.appendChild(t);
  z1.appendChild(s);
  z2.appendChild(r);
  document.getElementById(myTr[i]).appendChild(z);
  document.getElementById(myTr[i]).appendChild(z1)
  document.getElementById(myTr[i]).appendChild(z2)
}
}
<button onclick="myFunction()">Create</button>

定义 myTr 后似乎可以工作。并且 - 正如 Carsten Løvbo Andersen 已经提到的 - 你的 for 循环需要 运行 到给定单元格的 all 元素。我用 cell1.length.

替换了你的 3

let cell = ["a","b","c","x"];
let cell1 = ["d","e","f","y"];
let cell2 = ["g","h","i","z"];
const myTr=["a","b","c","d"];

function cmFunction(arr){
  const transp=arr[0].map(a=>Array());
  arr.forEach((ar,i)=>ar.forEach((a,j)=>transp[j][i]=a))
  document.body.innerHTML+='<table class="myTable"><tbody>'
   +transp.map((r,i)=>'<tr class="'+myTr[i]+'"><td>'+r.join("</td><td>")+"</td></tr>").join("\n") 
   +'</tbody></table>';
}
function myFunction() {
  var x = document.createElement("TABLE");
  x.setAttribute("id", "myTable");
  document.body.appendChild(x);
for(let i=0; i< cell1.length; i++){
  var y = document.createElement("TR");
  y.setAttribute("id", myTr[i])
  document.getElementById("myTable").appendChild(y);
  var z = document.createElement("TD");
  var t = document.createTextNode(cell[i]);
  var z1 = document.createElement("TD");
  var s = document.createTextNode(cell1[i]);
  var z2 = document.createElement("TD");
  var r = document.createTextNode(cell2[i]);
  z.appendChild(t);
  z1.appendChild(s);
  z2.appendChild(r);
  document.getElementById(myTr[i]).appendChild(z);
  document.getElementById(myTr[i]).appendChild(z1)
  document.getElementById(myTr[i]).appendChild(z2)
}
}
<button onclick="myFunction()">Create</button>
<button onclick="cmFunction([cell,cell1,cell2])">CreateNew</button>

我编辑脚本是为了向您展示整个事情可以用更简单的方式完成。在我的版本 cmFunction() 中,我将 id 属性替换为 class 属性,因为这将允许重复(如果重复单击“创建”)。