How to Create a Simple Linear Table in JavaScript
Sure! Here's an example of a simple linear table in JavaScript:
// Define the table data as an array of objects
var tableData = [
{ id: 1, name: 'John', age: 30 },
{ id: 2, name: 'Jane', age: 25 },
{ id: 3, name: 'Mark', age: 35 },
{ id: 4, name: 'Emily', age: 28 },
];
// Function to generate the table dynamically
function generateTable(data) {
// Get the table element from the HTML document
var table = document.getElementById('myTable');
// Create table headers
var thead = document.createElement('thead');
var headerRow = document.createElement('tr');
Object.keys(data[0]).forEach(function (key) {
var th = document.createElement('th');
th.appendChild(document.createTextNode(key));
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
// Create table rows and cells
var tbody = document.createElement('tbody');
data.forEach(function (row) {
var tr = document.createElement('tr');
Object.values(row).forEach(function (value) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(value));
tr.appendChild(td);
});
tbody.appendChild(tr);
});
table.appendChild(tbody);
}
// Call the function to generate the table
generateTable(tableData);
You can then add an HTML table element with an id 'myTable' in your HTML file where you want the table to be displayed:
<table id='myTable'></table>
This JavaScript code will dynamically generate a table using the provided table data array and append it to the HTML table element with the id 'myTable'. Each object in the table data array represents a row in the table, and each key-value pair in the object represents a cell in the table.
原文地址: https://www.cveoy.top/t/topic/p4VZ 著作权归作者所有。请勿转载和采集!