我想按以下顺序使用json文件中的数据填充表格:键,值和输入
例如row1-(serverIP | 12.34.56.78.90 | input)row2-(serverName | master1 | input)...
我不知道该怎么做。感谢您的帮助
Json
{
"original":
{
"serverIP":"12.34.56.78.90",
"serverName":"master1"
}
}
html/js
<table id="table">
<tr>
<th>KEY</th>
<th>VALUE</th>
<th>INPUT</th>
</tr>
</table>
<script>
fetch('data.json')
.then(response => response.json())
.then(data => {
buildTemplate(data);
})
.catch(error => console.error(error))
const buildTemplate = (data) => {
const table = document.getElementById('table');
const tbody = document.createElement("tbody");
const tr = document.createElement('tr');
for (const key in data.original) {
if (data.original.hasOwnProperty(key)) {
const element = key;
let td1 = document.createElement('td');
td1.innerText = element;
tr.appendChild(td1);
for (const key in data.original) {
if (data.original.hasOwnProperty(key)) {
const element = data.original[key];
let td2 = document.createElement('td');
td2.innerText = data.original[key];
let td3 = document.createElement('td');
let input = document.createElement('input');
td3.appendChild(input);
tr.appendChild(td2);
tr.appendChild(td3);
tbody.appendChild(tr);
table.appendChild(tbody);
}
}
}
}
}
</script>
答案 0 :(得分:1)
这对我有用(我删除了fetch,立即传递json)。这是函数:
const buildTemplate = (data) => {
const table = document.getElementById('table');
const tbody = document.createElement("tbody");
for (const key in data.original) {
if (data.original.hasOwnProperty(key)) {
let tr = document.createElement('tr');
let td1 = document.createElement('td');
td1.innerText = key;
tr.appendChild(td1);
let td2 = document.createElement('td');
td2.innerText = data.original[key];
tr.appendChild(td2);
let td3 = document.createElement('td');
let input = document.createElement('input');
td3.appendChild(input);
tr.appendChild(td3);
tbody.appendChild(tr);
table.appendChild(tbody);
}
}
}