【发布时间】:2018-02-25 04:26:23
【问题描述】:
我有包含 3 个对象的 JSON 文件:
[
{
"image": "assets/image.jpg",
"title": "Text",
"text": "Some text",
"date": "23/11/2013"
},
...
]
还有 3 个 HTML 元素:
<div class="blog-post">
<img src="" class="blog-image"/>
<h2 class="blog-title"></h2>
<p class="blog-text"></p>
<div class="blog-date"></div>
</div>
我知道如何从 1 个对象获取数据到 1 个 html 元素:
((() => {
const getJSON = (url, callback) => {
const xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = () => {
const status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
const blogTitle = document.querySelector('.blog-title');
const blogText = document.querySelector('.blog-text');
const blogDate = document.querySelector('.blog-date');
const blogImage = document.querySelector('.blog-image');
getJSON('/test-data.json', (err, data) => {
if (err != null) {
return false;
} else {
blogImage.src = data.image;
blogTitle.innerText = data.title;
blogText.innerText = data.text;
blogDate.innerText = data.date;
}
});
}))();
但是我怎样才能使 json 文件中的所有对象循环并将数据插入到 html 元素中呢?
【问题讨论】:
-
你有多个
blog-post类的 DIV 元素吗?如果是这样,您如何确定哪个 JSON 数据数组条目与哪个.blog-post分区对应?还是需要为 JSON 数据中的每个条目创建新的分区? -
我有多个带有 blog-post 类的 DIV 元素。可能,创建两个数组并附加 [i] > [i],但我不知道解决这个问题的最佳方法是什么——这就是我创建问题的原因。 :)
标签: javascript html arrays json loops