从div ID获取所有图像并添加链接
我在构建一个 JavaScript 来从 div ID 获取所有图像,并在每个缩略图上添加指向大图像的链接时遇到一些困难。这是我的代码。
<html>
<head>
<script>
function addGallery(){
var getDivId = document.getElementById("imgContainer");
var images = getDivId.getElementsByTagName("img").innerHTML;
for(var i=0; i<images.length; i++) {
getDivId.innerHtml = "<a id='g2Image' href='big/" + images[i].src + "'>" + images[i].src + "</a>";
}
}
</script>
</head>
<body onload='addGallery()'>
<div id="imgContainer">
<img src="/images/galleries/img1.jpg" alt="" width="125" height="100" />
<img src="/images/galleries/img1.jpg" alt="" width="125" height="100" />
<img src="/images/galleries/img1.jpg" alt="" width="125" height="100" />
<img src="/images/galleries/img1.jpg" alt="" width="125" height="100" />
<img src="/images/galleries/img1.jpg" alt="" width="125" height="100" />
</div>
</body>
</html>
先感谢您! 问候。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在每个循环中分配innerHTML,而不连接现有的HTML。
更改:
至
You are assigning innerHTML in each loop without concatenating the existing HTML.
Change:
to
嗯...您实际上是在尝试从数组中获取对象属性,该属性不存在:
应该更改为:
Um... you're actually attempting to grab an object property from an array, which doesn't exist:
Should be changed to:
编辑2
请注意,在 IE 中,
image.src
值将是图像的完整路径,因此您不能只在它们前面添加“big/”。编辑
哎呀,没有看到您添加了 A 元素。大概您希望图像位于链接内。除了innerHTML,您还可以使用 DOM 方法来创建链接:
还有一个 document.images 集合 即文档中的所有图像,但您可能只需要 div 中的图像。
Edit 2
Note than in IE, the
image.src
value will be the full path of the image so you can't just prepend 'big/' to them.Edit
Oops, didn't see that you were adding A elements. Presumably you want the images to be inside the link. Instead of innerHTML, you can use DOM methods to creat the links:
There is also a document.images collection that is all the images in the document, but likely you only want those in the div.