猿问

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

我是一名 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);

这是正确的解决方案吗?或者还有其他方法可以解决这个问题吗?


绝地无双
浏览 94回答 2
2回答

翻过高山走不出你

您可以使用URL来避免连接先前的time参数:setInterval(function() {&nbsp; var images = document.getElementsByTagName('img');&nbsp; for (var i = 0; i < images.length; i++) {&nbsp; &nbsp; var dt = new Date();&nbsp; &nbsp; console.log(dt); //does not display anything on the console&nbsp; &nbsp; var img = images[i];&nbsp; &nbsp; if (img.id != 'MainIMAGE') // reload all images except image with id MainIMAGE&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; const url = new URL(img.src);&nbsp; &nbsp; &nbsp; url.search = 'time=' + dt.getTime();&nbsp; &nbsp; &nbsp; img.src = url.href;&nbsp; &nbsp; &nbsp; console.log(img.src + ' ' + dt); // does not display anything as well&nbsp; &nbsp; }&nbsp; }}, 1000);<img src="https://placeimg.com/200/200/any" />

开心每一天1111

我建议使用searchParams,而不是搜索const images = [...document.querySelectorAll('img:not(#MainIMAGE)')]; // assuming no dynamic images insertedsetInterval(() => {&nbsp; images.forEach(img => {&nbsp; &nbsp; const url = new URL(img.src);&nbsp; &nbsp; url.searchParams.set('time', new Date().getTime());&nbsp; &nbsp; img.src = url.href;&nbsp; })}, 2000);<img src="https://placeimg.com/100/100/any" /><br/><img id="MainIMAGE" src="https://placeimg.com/200/200/any" />
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答