我有一个这样的简单表:
<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>
有可能吗?
感谢。
答案 0 :(得分:1)
只需循环遍历数据并相应地更改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>
答案 1 :(得分:0)
使用 jQuery
:
var jsonObj = {
"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"
}
}
};
for (var i in jsonObj.datas) {
$("#"+i).append(jsonObj.datas[i].text);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<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>
</table>