【问题标题】:Set the src of an image with jQuery from a site that provides a different image with each refresh使用 jQuery 从一个站点设置图像的 src,该站点在每次刷新时提供不同的图像
【发布时间】:2019-10-05 18:23:09
【问题描述】:

我想从This Person Does Not Exist 为 DOM 上的多个 img 对象动态加载 src。

使用 jquery attr 函数时,每个 img 对象都包含相同的图像。我希望每个对象都包含一个“刷新”的图像。

我已经成功地使用setTimeout 让它工作,但如果我不必等待它们加载,我会更喜欢。

$(document).ready(function() {
    var time = 0;

    $('.imgDNE').each(function(e) {
        time+=2000;
        var obj = $(this);
        window.setTimeout(function() {
            $(obj).attr("src","https://thispersondoesnotexist.com/image?"+ new Date().getTime());
        },time);
    });
});

【问题讨论】:

    标签: javascript jquery image src


    【解决方案1】:

    尝试使用 DOM 属性的纯 JS 解决方案:

    document.addEventListener("DOMContentLoaded", function() {
        var myImg = document.getElementsByClass("imgDNE")
        myImg[0].setAttribute("src", "https://thispersondoesnotexist.com/image#" + new Date.now());
    });
    

    在 URL 的末尾使用# 来“欺骗”浏览器的缓存而不绕过上游缓存

    您也可以在这里尝试这个技巧,将src 属性设置为自身:

     myImg.src = myImg.src;
    

    【讨论】:

    • 实际的类名函数是document.getElementsByClassName('imgDNE'); 其次,我试图填充未知数量的对象,而不仅仅是一个。我已经在原始代码中实现了一个缓存傻瓜...?"+ new Date().getTime()
    猜你喜欢
    • 2016-03-28
    • 2021-09-02
    • 2017-03-29
    • 2011-07-28
    • 2013-04-18
    • 2019-03-29
    • 1970-01-01
    • 2014-04-12
    • 2015-06-02
    相关资源
    最近更新 更多