我真的不确定我在这里做错了什么。我的代码对我有意义,但我想我只是一个初学者。看起来如此简单但我无法弄清楚。任何帮助都会很棒,拜托并谢谢。
请阅读代码注释,了解我正在尝试做的规范。
JSON代码:
{"images":[
{
"bannerImg1":"./images/effy.jpg"
}]}
JavaScript的:
$.getJSON('data.json', function(data) { // Get data from JSON file
for (var i in data.images) {
var output+=data.images[i].bannerImg1; // Place image in variable output
}
document.getElementById("banner-img").innerHTML=output;}); // Display image in the img tag placeholder
HTML:
<div class="banner-section">
<!-- Image should load within the following img tag -->
<img class="banner-img" alt="effy">
</div>
答案 0 :(得分:4)
创建一个Image对象(带有所需属性)并将其添加到exiting div
var data = {
"images": [{
"bannerImg1": "http://i.stack.imgur.com/HXS1E.png?s=32&g=1"
},
{"bannerImg1" : "http://i.stack.imgur.com/8ywqe.png?s=32&g=1"
}]
};
data.images.forEach( function(obj) {
var img = new Image();
img.src = obj.bannerImg1;
img.setAttribute("class", "banner-img");
img.setAttribute("alt", "effy");
document.getElementById("img-container").appendChild(img);
});
<div class="banner-section" id="img-container">
</div>
答案 1 :(得分:2)
<div id="picture"></div>
将img标记附加到div
//code
success : function(data) {
var returnData = jQuery.parseJSON(data);
$("#picture").append("<img src=\" + returnData.img_url + "\" />");
});
//code if any
答案 2 :(得分:0)
试试这个:
$.getJSON('data.json', function(data) { // Get data from JSON file
try{
var json = $.parseJSON(data);
for (var i =0; i< json.images.length; i++) {
var output+=json.images[i].bannerImg1; // Place image in variable output
}
document.getElementById("banner-img").innerHTML=output;
}catch{}
});