【问题标题】:Why does not IMG tag work when I iterate over array of image links and show them with innerHTML?当我遍历图像链接数组并使用 innerHTML 显示它们时,为什么 IMG 标记不起作用?
【发布时间】:2015-05-24 18:37:00
【问题描述】:

我想知道为什么这段代码不向我显示图像?我在运行代码后检查了 view page sourcefirebugimg 标签出现,但它们不加载数组中提供的图像。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width; initial-scale=0.8; maximum-scale=0.8;" />
<script>
var links = [
"1.jpg",
"2.jpg",
"3.jpg",
"4.jpg",
"5.jpg",
"6.jpg"
];
var images = "";
function showImages()
{
    for(i = 0; i < links.length; i++)
    {
        images += '<img id="myImage" href="'+links[i]+'">';
    }
    document.getElementById("container").innerHTML = images;
}
</script>
<style type="text/css">
.ph{border-style: solid;border-width: 5px;}
img.resize{max-width:100px;max-height:300px;margin:auto;}
#container{width: 500px;margin:auto; }
</style>
<title>Images</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<div id="container"><script>showImages();</script></div>
</body>
</html>

【问题讨论】:

  • 图片是否存在于该位置?
  • 是的,无论如何,我已经发送到互联网链接。它们存在,我已经测试过了。我使用了另一种方法stackoverflow.com/questions/29488371/…,它确实有效,但我想知道上面的代码有什么问题,无法显示图像。
  • 首先,您正在创建具有相同 ID 的元素,这是错误的。其次,图像没有href 属性,它们有src 属性
  • @adeneo 感谢您指出相同的 id 问题!

标签: javascript jquery html


【解决方案1】:

图像元素需要src 而不是href 属性。 所以改变

images += '<img id="myImage" href="'+links[i]+'">';

images += '<img id="myImage" src="'+links[i]+'">';

JSFiddle

【讨论】:

  • 哇!我可能已经失明了! :)
猜你喜欢
  • 2020-04-01
  • 2012-03-20
  • 1970-01-01
  • 2022-11-12
  • 2016-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多