我想在页面上添加指向所有图片的链接。链接应指向图像源。
例如,从中:
<img src="foo.jpg">
我想得到这个:
<a href="foo.jpg"><img src="foo.jpg"></a>
我尝试像下面这样做,但似乎没有任何事情发生。那么我是否必须以某种方式在某处添加新的“a”元素?
var images = document.getElementsByTagName('img');
for (var image in images) {
var a = document.createElement('a');
a.href = image.src;
a.innerHtml = image;
}
答案 0 :(得分:2)
您只需创建Tag
,但不要将其插入Document
。
您可以使用Node中的replaceChild
方法替换Img
代码。
答案 1 :(得分:2)
您正在迭代此行中images
的索引(0,1,2,...):
for (var image in images) {
如果image
是HTML元素,则此行仍然无效,因为innerHTML
属性需要HTML文本,而不是对象:
a.innerHtml = image;
最后,您忽略了将锚添加到文档中。
这是一种正确的方法:
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; ++i) {
var img = images[i];
var a = document.createElement('a'); // Make a new anchor.
a.href = img.src; // Point it at the image source.
img.parentNode.replaceChild(a, img); // Replace the image with the anchor.
a.appendChild(img); // Make the image a child of the anchor.
}
<img src="http://i.stack.imgur.com/bcOyt.png">
<img src="http://i.stack.imgur.com/IPkNZ.png">
<img src="http://i.stack.imgur.com/Kd7GM.png">
答案 2 :(得分:-1)
对于每个循环在javascript中有点奇怪,你需要访问这样的对象:
for (var image in images) {
var a = document.createElement('a');
a.href = images[image].src;
a.innerHtml = images[image];
a.appendChild(images[image]);
// then of course you need to replace the img with the anchor containing the image
images[image].parentNode.replaceChild(a, images[image]);
}
一般来说:
for(var obj in list) {
var current = list[obj];
}
答案 3 :(得分:-1)
我可以建议jQuery
吗?
由于浏览器限制,以下示例在沙箱中不起作用,但应该在您控制的站点上运行。此外,根据具体情况,浏览器可能会阻止弹出窗口。但是,对于网页自己的域中的链接,这可能是更好的解决方案,因为您避免操纵DOM。
$(function () {
$('img').on('click', function () {
var win = window.open($(this).attr('src'), '_blank')
win.focus()
})
})
img {
border: 1px solid blue;
cursor: pointer;
float: left;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
这是另一种方法,将您最初请求的所有图像包装在a
标记中:
$(function () {
$('img').wrap(function () {
return '<a href="' + $(this).attr('src') + '"></a>'
})
})
img {
border: 1px solid blue;
cursor: pointer;
float: left;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">
<img src="https://placehold.it/100x100">