我JSON文件有3個對象:插入數據的HTML元素
[
{
"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元素取DATAS :
((() => {
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數據中的每個條目創建新的分區? – traktor53
我有多個博客文章類DIV元素。可能,創建兩個數組並追加[i]> [i],但我不知道解決此問題的最佳方法是什麼 - 這就是爲什麼我創建了一個問題。 :) –