如何使用 JavaScript 获取页面上所有图像的 href?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6414060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the href of all images on a page using JavaScript?
提问by joelson
Is it possible for me to get the href of all images on a page using JavaScript? This code gives me the src for those images, but I want to return the href for them.
我可以使用 JavaScript 获取页面上所有图像的 href 吗?此代码为我提供了这些图像的 src,但我想为它们返回 href。
function?checkimages()?{
? ?? var?images?=?document.images;
? ?? for?(var?i=0;?i<images.length;?i++){
? ? ? ??var?img?=images[i].src;
alert(img);
}
}
回答by kapa
As @Kyle points out, an img
does not have an href
attribute, they only have 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).
正如@Kyle 指出的那样, animg
没有href
属性,它们只有src
. 只是猜测,但您的图像可能有一个链接 ( 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);
}
}
}
回答by rob
var a = document.getElementsByTagName("IMG");
for (var i=0, len=a.length; i<len; i++)
alert (a[i].src);
回答by Kyle Undefined
Images don't have an href
attribute, that applies only to anchors (a
).
图像没有href
仅适用于锚点 ( a
)的属性。
回答by Senad Me?kin
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);
}
}