将createtable onclick Event更改为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"
}
]
}

当我将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>

最新更新