简体   繁体   English

如何使用 Javascript 获取特定页面上的所有图像源

[英]How to get all the image sources on a particular Page using Javascript

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.但是,当我 go 在我的页面上编写此 function 时,它只会找到第一张图像然后停止。 What is the best way to have it print all of the image src's on the current page?让它在当前页面上打印所有图像 src 的最佳方法是什么? Thanks!谢谢!

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

It may help you...它可能会帮助你...

img=document.getElementsByTagName("img");
for(i=0; i<img.length; i++) {
    imgp = imgp + img[i].src + '<br/>'; 
}
document.write(imgp);

I searched the whole web for a solution to this, maybe this will help if someone else searches the same.我搜索了整个 web 以寻找解决方案,如果其他人搜索相同的内容,这可能会有所帮助。

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,安扬卡

To print on current page (replace content):在当前页面上打印(替换内容):

document.write(`<pre>${JSON.stringify(Array.prototype.map.call(document.getElementsByTagName("img"), img => img.src), null, 2)}</pre>`);

To save in array:要保存在数组中:

const imgs = Array.prototype.map.call(document.getElementsByTagName("img"), img => img.src);

To just console dir/log directly:直接控制台目录/日志:

console.dir(Array.prototype.map.call(document.getElementsByTagName("img"), img => img.src));
console.log(Array.prototype.map.call(document.getElementsByTagName("img"), img => img.src));

Make it simple:让它简单:

console.log(document.body.getElementsByTagName('img'));

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

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