简体   繁体   中英

Is this right way when using HTML table in JavaScript?

Is this right way when using HTML table in JavaScript?

I have to creating html table as dynamic but i have no idea.

Please tell me a good idea!

<tbody>
  <tr>
    <td>row1</td>
    <td>val1</td>
    <td>val2</td>
    <td>val3</td>
    <td>val4</td>
  </tr>
  <tr>
    <td>row2</td>
    <td>val1</td>
    <td>val2</td>
    <td>val3</td>
    <td>val4</td>
  </tr>
  ...
</tbody>


var tableArr = {
  row1: [],
  row2: [],
};

tableArr.row1.push('1');
tableArr.row1.push('2');
tableArr.row1.push('3');
tableArr.row1.push('4');

tableArr.row2.push('1');
tableArr.row2.push('2');
tableArr.row2.push('3');
tableArr.row2.push('4');

for (var row in tableArr) {
    console.log(row);
    for (var i=0; i<tableArr[row].length; i++) {
        console.log(tableArr[row][i]);
    }
}

Please tell me a good idea! :D

You can use javascript methods to create table and rows etc.

 var tableRef = document.createElement('table'); for (var i = 0; i <= 5; i++) { var newRow = tableRef.insertRow(i); var newCell = newRow.insertCell(0); var newText = document.createTextNode('New top row #' + i); newCell.appendChild(newText); } document.body.appendChild(tableRef); 

You need to access DOM and modify HTMLTableElement in order to chage HTML tables from JavaScript.

Your initial HTML code:

<table id="myTable">
</table>

Your JavaScript code:

// Find a <table> element with id="myTable":
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";

Your HTML code after JavaScript updates:

<table id="myTable">
<tr>
<td>NEW CELL1</td>
<td>NEW CELL2</td>
</tr>
</table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM