首页 > 解决方案 > 如何使用javascript从数组创建表

问题描述

我试图弄清楚如何仅使用 javascript 将具有多个变量的数组传输到 HTML 表中。到目前为止,我的 javascript 代码正在将所有内容呈现到页面上,我不希望标签之类的显示。结果应该类似于[table_example_image]

指令是:

使用 JavaScript,遍历数组中的项目,并在网页部分下的表格中动态显示集合。

整个表格(包括用示例中的实际图像替换任何真/假文本)和内容应该使用 JavaScript 生成和输出。

在表中,为数组集合中的每个属性创建一个元素(例如标题、作者、已读)- 列数和文本应基于 JavaScript 动态生成,而不是“硬编码”。

为每个值创建和附加一个 使用 JavaScript 为 HTML 文档部分中的表格附加和创建样式规则。

任何提示将不胜感激!

    var books = [
    {
        title: 'The Stranger',
        author: 'Albert Camus',
        alreadyRead: true
    },
    {
        title: 'Binging with Babish',
        author: 'Andrew Rea',
        alreadyRead: true
    },
    {
        title: 'You Suck at Cooking: The Absurdly Practical Guide to Sucking Slightly Less at Making Food: A Cookbook',
        author: 'You Suck at Cooking',
        alreadyRead: false
    }];

createTable();

function createTable() {
    var table = document.createElement("table");  //makes a table element for the page

    table += "<tr class='firstRow'><th>Title</th><th>Author</th><th>Read?</th></tr>";  //adds the first row that contains the sections for the table

    for (var i = 0; i < books.length; i++)  //loops through the array 
    {
        //add info from the array into this
        table += "<tr><td>" + books[i].title + "</td><td>";
    }

    document.body.append(table);
}

标签: javascript

解决方案


您当前正在尝试将字符串添加到表对象。看看这个页面。

function createTable() {

    var headers = ["Title", "Author", "Read?"];
    var table = document.createElement("TABLE");  //makes a table element for the page
        
    for(var i = 0; i < books.length; i++) {
        var row = table.insertRow(i);
        row.insertCell(0).innerHTML = books[i].title;
        row.insertCell(1).innerHTML = books[i].author;
        row.insertCell(2).innerHTML = books[i].alreadyRead;
    }

    var header = table.createTHead();
    var headerRow = header.insertRow(0);
    for(var i = 0; i < headers.length; i++) {
        headerRow.insertCell(i).innerHTML = headers[i];
    }

    document.body.append(table);
}

推荐阅读