如何在页面上的每张图片周围添加 link?

How can I add a link around every image on a page?

我想为页面上的所有图片添加 link。 link 应该指向图像源。

例如,来自这个:

<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;
}

因为 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];
}

您只是创建了 Tag,但没有将其插入到 Document。 您可以使用 Node 中的 replaceChild 方法来替换 Img 标签。

您正在迭代 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">

我可以建议 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">