将 JSON 数据附加到 HTML 元素
Appending JSON data to an HTML element
我正在尝试:
使用 $.get
获取 JSON 数据
将该数据附加到 HTML 元素 $('photos') 以便使用外部 JSON 文件而不是内嵌 HTML.
我没有收到任何控制台错误,也没有显示图像。任何帮助将不胜感激。非常感谢。我有一个警报来检查 JSON 是否已加载,它加载正常 - 只是没有更改任何数据。
这是我当前的设置:
(JSON): photoData.json
{ "photos": {
"1": {
"href": "./photos/photo1.JPG",
"src": "photos/photo1.JPG",
},
"2": {
"href": "./photos/photo2.JPG",
"src": "photos/photo2.JPG",
},
"3": {
"href": "./photos/photo3.JPG",
"src": "photos/photo3.JPG",
},
"4": {
"href": "./photos/photo4.JPG",
"src": "photos/photo4.JPG",
},
"5": {
"href": "./photos/photo5.JPG",
"src": "photos/photo5.JPG",
}}}
jQuery:
$.get("./data/photoData.json", function(photos){
alert("Data Loaded: " + photos);
let htmlStr = "";
for (let i = 0; i < photos.length; i++){
htmlStr += `<figure><a href="${photos[i].href}"><img src = "${photos[i].src}"></img></a></figure>`
}
$('Photos').html(htmlStr);});
photos
是对象的对象而不是数组。所以使用 for...in
代替:
$.get("./data/photoData.json", function(data) {
const photos = data.photos;
let htmlStr = '';
for (let photo in photos) {
htmlStr += `<figure><a href="${photos[photo].href}"><img src="${photos[photo].src}"></img></a></figure>`
}
});
评论中提出了一些问题:$('Photos')
不是有效的 jQuery 选择器。我怀疑您有一个名为 Photos
的元素 - 您只需要将哈希添加到选择器:$('#Photos')
.
我正在尝试:
使用 $.get
获取 JSON 数据
将该数据附加到 HTML 元素 $('photos') 以便使用外部 JSON 文件而不是内嵌 HTML.
我没有收到任何控制台错误,也没有显示图像。任何帮助将不胜感激。非常感谢。我有一个警报来检查 JSON 是否已加载,它加载正常 - 只是没有更改任何数据。
这是我当前的设置:
(JSON): photoData.json
{ "photos": {
"1": {
"href": "./photos/photo1.JPG",
"src": "photos/photo1.JPG",
},
"2": {
"href": "./photos/photo2.JPG",
"src": "photos/photo2.JPG",
},
"3": {
"href": "./photos/photo3.JPG",
"src": "photos/photo3.JPG",
},
"4": {
"href": "./photos/photo4.JPG",
"src": "photos/photo4.JPG",
},
"5": {
"href": "./photos/photo5.JPG",
"src": "photos/photo5.JPG",
}}}
jQuery:
$.get("./data/photoData.json", function(photos){
alert("Data Loaded: " + photos);
let htmlStr = "";
for (let i = 0; i < photos.length; i++){
htmlStr += `<figure><a href="${photos[i].href}"><img src = "${photos[i].src}"></img></a></figure>`
}
$('Photos').html(htmlStr);});
photos
是对象的对象而不是数组。所以使用 for...in
代替:
$.get("./data/photoData.json", function(data) {
const photos = data.photos;
let htmlStr = '';
for (let photo in photos) {
htmlStr += `<figure><a href="${photos[photo].href}"><img src="${photos[photo].src}"></img></a></figure>`
}
});
评论中提出了一些问题:$('Photos')
不是有效的 jQuery 选择器。我怀疑您有一个名为 Photos
的元素 - 您只需要将哈希添加到选择器:$('#Photos')
.