为了账号安全,请及时绑定邮箱和手机立即绑定

无需刷新整个页面即可更新网页中的图像

无需刷新整个页面即可更新网页中的图像

绝地无双 2022-05-22 13:53:57
我是一名 JavaScript 初学者。我正在使用烧瓶将我的 python 代码与前端(plainJS、HTML 和 CSS)集成。基本上,我在左侧有一个包含图像(或者更确切地说是图像的图块)的网页,在右侧有搜索结果。当用户选择图像中的特定图块时,它会被发送到后端进行处理,将结果(外观相似的图块)保存到文件夹中。这些将在网页的右侧自动检索。这样做的问题是:当我运行烧瓶应用程序时,页面首先被加载,并且由于开头的结果文件夹包含上一个会话的图像,所以它们被加载了。此外,在 python 处理完成后,我必须手动刷新页面才能加载结果。我试过:编写一个 setInterval 函数,每隔 5 秒更新一次图像的来源,这样当新结果到达时,它们可以自动显示。代码写在下面。显然这个函数根本不起作用(我输入了 console.log() 语句,但它们没有显示任何内容):JAVASCRIPT--------->setInterval(function(){    var images=document.getElementsByTagName('img');    for(var i=0;i<images.length;i++){      var dt=new Date();      console.log(dt); //does not display anything on the console      var img=images[i];      if(img.id!='MainIMAGE')    // reload all images except image with id MainIMAGE        {           img.src=img.src+"?"+dt.getTime();           console.log(img.src);  // does not display anything as well        }   }},5000);这是正确的解决方案吗?或者还有其他方法可以解决这个问题吗?
查看完整描述

2 回答

?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

您可以使用URL来避免连接先前的time参数:


setInterval(function() {

  var images = document.getElementsByTagName('img');

  for (var i = 0; i < images.length; i++) {

    var dt = new Date();

    console.log(dt); //does not display anything on the console

    var img = images[i];

    if (img.id != 'MainIMAGE') // reload all images except image with id MainIMAGE

    {

      const url = new URL(img.src);

      url.search = 'time=' + dt.getTime();

      img.src = url.href;

      console.log(img.src + ' ' + dt); // does not display anything as well

    }

  }

}, 1000);

<img src="https://placeimg.com/200/200/any" />


查看完整回答
反对 回复 2022-05-22
?
开心每一天1111

TA贡献1836条经验 获得超13个赞

我建议使用searchParams,而不是搜索


const images = [...document.querySelectorAll('img:not(#MainIMAGE)')]; // assuming no dynamic images inserted

setInterval(() => {

  images.forEach(img => {

    const url = new URL(img.src);

    url.searchParams.set('time', new Date().getTime());

    img.src = url.href;

  })

}, 2000);

<img src="https://placeimg.com/100/100/any" /><br/>


<img id="MainIMAGE" src="https://placeimg.com/200/200/any" />


查看完整回答
反对 回复 2022-05-22
  • 2 回答
  • 0 关注
  • 93 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号