gpt4 book ai didi

javascript - 如何将图像填充为链接,并将其作为 JSON 对象存储在数组中?

转载 作者:行者123 更新时间:2023-12-02 17:26:27 26 4
gpt4 key购买 nike

请单击我的 JSFiddle 链接以查看我正在尝试执行的操作的代码。您会注意到,我将图 block 、图像和链接存储为 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 .

关于javascript - 如何将图像填充为链接,并将其作为 JSON 对象存储在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23462351/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com