写在表 using Javascript with document.getElementById(“Table”).rows[i].cells[j].??? Or any other possible ways

问题描述 投票:-2回答:2

我怎样才能在使用Javascript与<td>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);
javascript html-table simple-html-dom
2个回答
0
投票

create table using JavaScript

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

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>
© www.soinside.com 2019 - 2024. All rights reserved.