javascript - 将 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"
}
]
}
解决方案
当我将 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>
推荐阅读
- javascript - 将 html 元素转换为文件
- amazon-web-services - AWS DynamoDB 查询:查找匹配记录的计数
- django - Django 自定义表单和 GenericView
- java - 为什么我不能用渐变色android更改图标颜色和文本底部导航
- ada - 如何在 Windows 下分发 GtkAda 应用程序?
- javascript - 如何在Nodejs中将base64解码为图像?
- angular - 如何使用 ng2-charts 获得多个图表(条形图和折线形图)?
- reactjs - 如何通过反应测试库获得代码覆盖率
- javascript - 如何使用 Javascript 伪造 Html5 GeoLocation API?
- c# - 从另一个列表中添加一个列表中的数据可以保存第一个列表的引用