我正在尝试使用我提取到JSON文件中的信息创建一个图像库。我刚刚学习JS,这是我最大的挑战。
图库我将稍后插入这些数据以及图像。此信息来自我通过discogs记录的集合。
很多网站都为我提供了一些解决方案,但还没有完全解决。
这是我拥有的JSON数据的一个例子
https://github.com/zephur/discogs-onhand-record-collection/blob/master/collection.json
使用此信息从java脚本创建div元素,以及灵活的100-200px ^ 2左右的图像。
如果您已经处理了提取位,那么它就是渲染部分。如果你还没有处理过读取位,那么this might help you with that。现代浏览器实现了一个非常强大的fetch接口,您可以在其中使用
fetch('http://example.com/movies.json')
.then(function(response) {
// here, we take the response from the fetch request, and convert it to a JSON
// object, and pass that to the NEXT step.
return response.json();
})
.then(function(myData) {
// taking that JSON object, we can do something with it.
// In our particular case, we want to take that JSON, and turn it into a
// bunch of DOM nodes.
console.log(JSON.stringify(myData));
});
但是在你的情况下,不是简单地在最后一点使用console.log(),你会想要做一些不同的事情。您希望迭代数组中的每个节点,并将其转换为实际的HTML节点。
所以第一步是对该数组的每个成员做一些事情:
myData.forEach(function(item){ ...});
这让我们可以对数组中的每个对象执行某些操作。因为它们是对象,我们可以使用Template Literals轻松地从它们构建HTML元素。这些是一个字符串,可以动态插入javascript变量。就像是:
myData.forEach(function(item){
let myContainer = `<div class='album'>
<h2>${item.Artist} : ${item.Title}</h2>
<p class='formats'>${item.Format}</p>
<figure>
<img src=''>
<figcaption>${item.Title}</figcaption>
</figure>
</div>`;
});
到目前为止一切运作良好,但仍然缺少一些东西。我们已经将HTML DOM节点创建为字符串,但我们仍然需要将其添加到容器元素中。为方便起见,我们假装我们有一个类main-container
的容器:
myData.forEach(function(item){
// this builds the HTML DOM node for our current item
let myContainer = `<div class='album'>
<h2>${item.Artist} : ${item.Title}</h2>
<p class='formats'>${item.Format}</p>
<figure>
<img src=''>
<figcaption>${item.Title}</figcaption>
</figure>
</div>`;
// This line appends the string we just built into the DOM.
document.querySelector(".main-container").innerHTML += myContainer;
});
现在,只缺少两件事:用CSS来设置所有这些(最好的方式是?设计.album
,并设置任何后代节点的样式),以及来自哪里的图像?
首先,您的数据不是JSON。它是一组JSON。如果要列出元素,这可能有效:
让我们创建一个包含属性名称的数组,以便轻松列出它
var keys = Object.keys(data[0]);
列出数组中的每个项目:
for(var i = 0; i < data.length; i++){
for(var j = 0; j < keys.length; j++){
document.getElementById("my-div").innerHTML += keys[j] + ": " + data[i][keys[j]] + "<br>";
}
document.getElementById("my-div").innerHTML += "<br>"
}