Javascript 如何使用Javascript获取特定页面上的所有图像源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5809051/
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 to get all the image sources on a particular Page using Javascript
提问by Chris
I am using a simple script to find an image on a page and get its source.
我正在使用一个简单的脚本在页面上查找图像并获取其来源。
function img_find() {
var img_find2 = document.getElementsByTagName("img")[0].src;
return img_find;
}
However when I go to write this function on my page it only finds the first image and then stops. What is the best way to have it print all of the image src's on the current page? Thanks!
但是,当我在页面上编写此函数时,它只会找到第一张图像然后停止。让它在当前页面上打印所有图像 src 的最佳方法是什么?谢谢!
回答by BalusC
You indeed told the code to do so. Don't do that. Just tell it to loop over all images and push the src of each in an array and return the array with all srcs instead.
你确实告诉代码这样做。不要那样做。只需告诉它循环遍历所有图像并将每个图像的 src 推送到数组中,然后返回包含所有 src 的数组。
function img_find() {
var imgs = document.getElementsByTagName("img");
var imgSrcs = [];
for (var i = 0; i < imgs.length; i++) {
imgSrcs.push(imgs[i].src);
}
return imgSrcs;
}
回答by Anjanka
I searched the whole web for a solution to this, maybe this will help if someone else searches the same.
我在整个网络上搜索了解决方案,如果其他人搜索相同的内容,这可能会有所帮助。
for(var i = 0; i< document.images.length; i++){
document.images[i].style.border = "1px solid #E0FDA6";
}
Meaning, search all images that have style tag (border in this example) and set all borders to E0FDA6 (useful to reset single highlighted images), but I guess it can be used for everything with style tag.
意思是,搜索所有带有样式标签(在本例中为边框)的图像并将所有边框设置为 E0FDA6(用于重置单个突出显示的图像),但我想它可以用于所有带有样式标签的图像。
Rg, Anjanka
Rg, 安詹卡
回答by Ashish Kumar
It may help you...
它可能会帮助你...
img=document.getElementsByTagName("img");
for(i=0; i<img.length; i++) {
imgp = imgp + img[i].src + '<br/>';
}
document.write(imgp);
回答by Sam
Make it simple:
让它变得简单:
console.log(document.body.getElementsByTagName('img'));