我是 Json 新手,正在尝试加载 Json 对象的一部分。结构为:
{
"Monday": {
"title": "Magic Monday",
"text": "On Magic Monday, all the food disappears.",
"image": "images/special.jpg",
"color": "red"
},
"Tuesday": {
"title": "Twofer Tuesday",
"text": "Two vegetables for the price of one!.",
"image": "images/special.jpg",
"color": "green"
}
}
我有一个变量 weekDay,我将使用它来查找正确的对象。找到后,我想在 HTML 中使用标题和文本的值。
到目前为止我有代码:
$.getJSON('data/specials.json', function (data) {
$.each(data, function (entryIndex, entry) {
var html = '<h4>' + entry['title'] + '</h4>';
html += '<p>' + entry['text'] + '</p>';
$('#details').append(html);
});
});
但我不知道如何仅从正确的工作日的对象中获取标题和文本。
提前致谢:)
最佳答案
如果你有
var weekDay = "Tuesday";
然后你可以简单地使用
var entry = data[weekDay];
然后
var title = entry.title;
或
var title = entry['title'];
This document解释如何访问对象属性。
关于javascript - 如何找到正确的 Json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13974741/