如何将图像填充为链接,这些链接都作为JSON对象存储在数组中

How to populate an image as a link which are both stored in an array as JSON objects?

本文关键字:链接 对象 JSON 存储 数组 图像 填充      更新时间:2023-09-26

请点击我的JSFiddle链接查看我正在尝试做的代码。正如您将注意到的,我将标题、图像和链接存储为JSON对象,但是当您运行我的代码时,它不会像在HTML文件中指定的那样将标题和图像显示为链接以及在属性中指定的链接。我研究这个问题已经有一段时间了,但我还是搞不明白,虽然这看起来应该是显而易见的事情。有人有什么想法、建议或解决方案吗?我尝试将JavaScript中的输出设置为",但这不起作用。

HTML:

<a id="food" class="thumbnail" target="_blank">
<img width="200" class="img-shadow">
<hr>
<h3></h3>
</a>
JavaScript:

var data={"food":[
{
    "title":"Pumpkin Spice Bread Recipe",
    "image":"img/bread.jpg",
    "link":"http://willowbirdbaking.com/2011/09/18/pumpkin-spice-pull-apart-
bread-with-butter-rum-glaze/"
    }
]}
var output="<ul>";
// Create a variable to temporarily store the data 
for (var i in data.food) {
    output+="<li>" + data.food[i].title + data.food[i].image +      data.food[i].link + "</li>";
}
output+="</ul>";
// Once we go through all of the elements in the array, 
// we use the output variable to populate the placeholder div.
document.getElementById("food").innerHTML=output;   

JSFiddle

提前感谢,非常感谢任何一点帮助。

您必须使用<img />标记输出图像。你的错误是你只是输出图像链接。

使用图片链接标签:var bob = "some text <img src='"+data.food[i].image+"' />";

试试这个:

var data={"food":[
{
    "title":"Pumpkin Spice Bread Recipe",
    "image":"img/bread.jpg",
    "link":"http://willowbirdbaking.com/2011/09/18/pumpkin-spice-pull-apart-
bread-with-butter-rum-glaze/"
    }
]}
var output="<ul>";
// Create a variable to temporarily store the data 
for (var i in data.food) {
    output+="<li>" + data.food[i].title + "<img src='"+data.food[i].image+"' /> " + data.food[i].link + "</li>";
}
output+="</ul>";
// Once we go through all of the elements in the array, 
// we use the output variable to populate the placeholder div.
document.getElementById("food").innerHTML=output;  

如果你想让你的图像成为链接,你必须把你的图像放入<a></a>标签,像这样:

for (var i in data.food) {
    output+="<li><a title='" + data.food[i].title + "' href='"+data.food[i].link+"'><img title='" + data.food[i].title + "' src='"+data.food[i].image+"' /></li>";
}

最终代码:

var data={"food":[
{
    "title":"Pumpkin Spice Bread Recipe",
    "image":"img/bread.jpg",
    "link":"http://willowbirdbaking.com/2011/09/18/pumpkin-spice-pull-apart-
bread-with-butter-rum-glaze/"
    }
]}
var output="<ul>";
// Create a variable to temporarily store the data 
for (var i in data.food) {
    output+="<li><a title='" + data.food[i].title + "' href='"+data.food[i].link+"'>" + data.food[i].title + "<img title='" + data.food[i].title + "' src='"+data.food[i].image+"' /></li>";
}
output+="</ul>";
// Once we go through all of the elements in the array, 
// we use the output variable to populate the placeholder div.
document.getElementById("food").innerHTML=output;  

和jsfiddle。

<a>标签内。你只需要一个href属性就可以让它看起来像一个真正的链接。