首页 > 解决方案 > 将 create table onclick 事件更改为 Onload Page

问题描述

晚安朋友们,我有这个想法,现在我一直在尝试将代码更改为 onload()。

我尝试了很多不同的方法,但没有一个适合我。

我会把我的代码放在这里,如果你能帮助我,我很感激,但告诉我怎么做,我不想你只给我完成代码。

HTML

<div>
    <button>Get</button>
    <div id="table"></div>
</div>
<script src="script.js"></script>
</body>
</html>

JS

let myTable = document.querySelector('#table');


var distribuidores;
fetch('http://localhost:3000/distribuidores')
    .then(res => res.json())
    .then(data => distribuidores = data)
    .then(() => console.log(distribuidores))

let headers = ['id', 'codBrid', 'descricao']

btnGet.addEventListener('click', () => {
    let table = document.createElement('table');
    let headerRow = document.createElement('tr');

    headers.forEach(headerText => {
        let header = document.createElement('th');
        let textNode = document.createTextNode(headerText);
        header.appendChild(textNode);
        headerRow.appendChild(header);
    });

    table.appendChild(headerRow);

    distribuidores.forEach(emp => {
        let row = document.createElement('tr');
        Object.values(emp).forEach(text => {
            let cell = document.createElement('td');
            let textNode = document.createTextNode(text);
            cell.appendChild(textNode);
            row.appendChild(cell);
        });

        table.appendChild(row);
    });

    myTable.appendChild(table);
});

json

{
       "distribuidores": [
        {
            "id": "1",
            "codint": "4613",
            "descricao": "HTMYS"
        },
        {
            "id": "2",
            "codint": "10325",
            "descricao": "MPB LTDA"
        }
    ]
}

标签: javascriptjson

解决方案


当我将 id 添加到按钮时,您的代码运行良好

let myTable = document.querySelector('#table');


var distribuidores = [
        {
            "id": "1",
            "codint": "4613",
            "descricao": "HTMYS"
        },
        {
            "id": "2",
            "codint": "10325",
            "descricao": "MPB LTDA"
        }
    ];


let headers = ['id', 'codBrid', 'descricao']

btnGet.addEventListener('click', () => {
    let table = document.createElement('table');
    let headerRow = document.createElement('tr');

    headers.forEach(headerText => {
        let header = document.createElement('th');
        let textNode = document.createTextNode(headerText);
        header.appendChild(textNode);
        headerRow.appendChild(header);
    });

    table.appendChild(headerRow);

    distribuidores.forEach(emp => {
        let row = document.createElement('tr');
        Object.values(emp).forEach(text => {
            let cell = document.createElement('td');
            let textNode = document.createTextNode(text);
            cell.appendChild(textNode);
            row.appendChild(cell);
        });

        table.appendChild(row);
    });

    myTable.appendChild(table);
});
<html>
<body>
<div>
    <button id=btnGet>Get</button>
    <div id="table"></div>
</div>
</body>
</html>


推荐阅读