使用Java脚本写入表

时间:2019-02-14 09:17:59

标签: javascript

我要写到表中,尤其是最上面一行和最左边一列,如象棋中有A1,A2等的棋子。我该如何写到表rows[i].cells[j].---中。我只是在努力写入表中。

document.getElementById("Table").rows[i].cells[j]. ??? ;

大家好,现在解决了。我使用.textContent。

2 个答案:

答案 0 :(得分:4)

您只能以这种方式进行操作:

var table = document.getElementById("myTable");

// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);

// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);

// Add some text to the new cells:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2"; 

或为每个单元格提供ID,然后插入值

答案 1 :(得分:1)

您可以在表格上使用querySelector选择器方法来使用nth-of-type方法:

//Generate table
var table = document.createElement("table");
table.className = "table";
for (var y = 1; y <= 8; y++) {
  //Create row
  var row = table.insertRow();
  for (var x = 1; x <= 8; x++) {
    //Create cell
    var td = row.insertCell();
    if (x % 2 != y % 2) {
      //Set background to distinguish cells
      td.style.backgroundColor = "#EEE";
    }
    //Show coordinates on mouse hover
    td.title = x + ":" + y;
  }
}
//Insert into document
document.body.appendChild(table);
//Write to specific row
table.querySelector("tr:nth-of-type(" + 2 + ") td:nth-of-type(" + 5 + ")").textContent = "1";
table.querySelector("tr:nth-of-type(" + 5 + ") td:nth-of-type(" + 2 + ")").textContent = "2";
td {
  min-width: 50px;
  min-height: 50px;
  height: 50px;
  text-align: center;
}