我有一个像这样的简单表格:
<table>
<tbody>
<tr>
<td id="2017-04-10"></td>
<td id="2017-04-11"></td>
<td id="2017-04-12"></td>
<td id="2017-04-13"></td>
</tr>
</tbody>
</table>
如何从这个 json 文件中插入与表中的日期相对应的值 text
?
"datas": {
"2017-04-10": {
"text": "My blue text",
"color": "blue"
},
"2017-04-11": {
"text": "My red text",
"color": "red"
},
"2017-04-12": {
"text": "My orange text",
"color": "orange"
},
"2017-04-13": {
"text": "My green text",
"color": "green"
}
}
所以期望的输出应该是:
<table>
<tbody>
<tr>
<td id="2017-04-10">My blue text</td>
<td id="2017-04-11">My red text</td>
<td id="2017-04-12">My orange text</td>
<td id="2017-04-13">My green text</td>
</tr>
</tbody>
</table>
可能吗?
谢谢。
最佳答案
只需循环数据并相应地更改 textContent
属性即可:
var data = {
"datas": {
"2017-04-10": {
"text": "My blue text",
"color": "blue"
},
"2017-04-11": {
"text": "My red text",
"color": "red"
},
"2017-04-12": {
"text": "My orange text",
"color": "orange"
},
"2017-04-13": {
"text": "My green text",
"color": "green"
}
}
};
Object.keys(data.datas).map(function (date) {
document.getElementById(date).textContent = data.datas[date].text;
});
<table>
<tbody>
<tr>
<td id="2017-04-10"></td>
<td id="2017-04-11"></td>
<td id="2017-04-12"></td>
<td id="2017-04-13"></td>
</tr>
</tbody>
</table>
你没有提到它,但我打赌你想使用这些颜色来改变文本颜色(或者做类似的事情),在这种情况下你可以修改里面的 style.color
属性你的循环:
var data = {
"datas": {
"2017-04-10": {
"text": "My blue text",
"color": "blue"
},
"2017-04-11": {
"text": "My red text",
"color": "red"
},
"2017-04-12": {
"text": "My orange text",
"color": "orange"
},
"2017-04-13": {
"text": "My green text",
"color": "green"
}
}
};
Object.keys(data.datas).map(function (date) {
var dateCell = document.getElementById(date);
dateCell.textContent = data.datas[date].text;
dateCell.style.color = data.datas[date].color;
});
<table>
<tbody>
<tr>
<td id="2017-04-10"></td>
<td id="2017-04-11"></td>
<td id="2017-04-12"></td>
<td id="2017-04-13"></td>
</tr>
</tbody>
</table>
关于javascript - 从 JSON 文件填充表内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43330807/