请点击我的JSFiddle链接,查看我正在尝试的代码。正如您将注意到的,我将tile,image和链接存储为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;
提前致谢,非常感谢任何帮助。
答案 0 :(得分:1)
您必须使用<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;
答案 1 :(得分:1)
它位于<a>
标记内。你只需要一个href属性就可以看起来像一个真正的链接。