使用Javascript和document.getElementById(“ Table”)。rows [i] .cells [j]编写表格。或任何其他可能的方式

时间:2019-02-09 19:29:05

标签: javascript html-table simple-html-dom

如何使用带有<td>的Javascript在表document.getElementById("Table").rows[i].cells[j]中编写代码?或其他任何可能的方式?

我想用JavaScript将内容写入<td></td>。 我在第一部分中使用了此代码,但是当我重用它时,它不起作用。如果有帮助,则该表是使用javascript生成的:

var cell = document.createElement("td");
var cellText = document.createTextNode(i+j);
cell.appendChild(cellText);

2 个答案:

答案 0 :(得分:0)

请参见create table using JavaScript

 var td = document.createElement('td');
    td.appendChild(document.createTextNode('text'))

答案 1 :(得分:0)

这是一个有效的示例,在标记中创建了一个基本表。

// save the table to a var
var table = document.getElementById('my_table');
// save table body to a var. select the first occurrence of tbody element with [0]
var tableRef = table.getElementsByTagName('tbody')[0];
// save new row tr to a variable. this generates a tr
var newRow = tableRef.insertRow(tableRef.rows.length);
// insert a cell into newRow at index 0, 1, and 2, the td's for this row
var newTD1 = newRow.insertCell(0);
var newTD2 = newRow.insertCell(1);
var newTD3 = newRow.insertCell(2);
// create a text node for the TD 
var tdText1 = document.createTextNode('cell text 1');
// add the text to the newly generated newTD1
newTD1.appendChild(tdText1);
// create a text node for the TD 
var tdText2 = document.createTextNode('cell text 2');
// add the text to the newly generated newTD2
newTD2.appendChild(tdText2);
// create a text node for the TD 
var tdText3 = document.createTextNode('cell text 3');
// add the text to the newly generated newTD3
newTD3.appendChild(tdText3);
/* table styles */
#my_table {
  border-collapse: collapse;
  border: 4px solid black;
  margin: 0 auto;
  text-align: center;
}

/* table tr, td styles */
#my_table th,
#my_table td {
  border: 2px solid black;
}

/* table header styles */
#my_table th {
  background-color: #33c6ff;
  color: #000;
  width: 33%;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>
</head>
<body>
  <table id='my_table'>
    <thead>
      <tr>
        <th id='table_header' colspan='3'>Table Title</th>
      </tr>
      <tr>
        <th>Header Row 1</th>
        <th>Header Row 2</th>
        <th>Header Row 3</th>
      </tr>
    </thead>
    <tbody id='table_body'>
    </tbody>
  </table> <!-- ends table -->
</body>
</html>