简体   繁体   English

如何使用JavaScript获取页面上所有图像的href?

[英]How can I get the href of all images on a page using JavaScript?

Is it possible for me to get the href of all images on a page using JavaScript? 我可以使用JavaScript获取页面上所有图像的href吗? This code gives me the src for those images, but I want to return the href for them. 这段代码给了我这些图像的src,但我想为它们返回href。

function checkimages() {
     var images = document.images;
     for (var i=0; i<images.length; i++){
        var img =images[i].src;
       alert(img);
     }
}

As @Kyle points out, an img does not have an href attribute, they only have src . 正如@Kyle指出的那样, img没有href属性,只有src Just guessing, but you might have a link ( a ) around your images, and its href stores the path to the big image (in case img is a thumbnail). 只是猜测,但你可能在你的图像周围有一个链接( a ),它的href存储了大图像的路径(如果img是缩略图)。

In this situation, you could use: 在这种情况下,您可以使用:

function checkImages() {
     var images = document.images;
     for (var i = 0; i < images.length; i++){
        if (images[i].parentNode.tagName.toLowerCase() === 'a') {
           console.log(images[i].parentNode.href);
        }
     }
}

jsFiddle Demo jsFiddle演示

var a = document.getElementsByTagName("IMG");
for (var i=0, len=a.length; i<len; i++)
  alert (a[i].src); 

图像没有href属性,仅适用于锚点( a )。

Probably you are looking for src attribute 可能你正在寻找src属性

function checkimages() {
     var images = document.getElementsByTagName('img');
     for (var i=0; i<images.length; i++){
        var img =images[i].getAttribute('src');
       alert(img);
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM