更改图像src而不重新加载页面

时间:2018-04-25 12:05:27

标签: javascript jquery html

我遇到了一个小问题,我觉得我要进入圈子。我目前正在开展一个项目,我需要在一些未定义的时间后用不同的图像更新<img> src(所以我不想用时间间隔重新加载图像和图像源每次都会有所不同)。我有15个图像需要在页面上显示,所以我想要实现的是当.html文件中的图像源更改为从服务器自动更新。 另外,我在循环中更新.html文件,因此每次迭代都会有一个新图像。 这对我来说听起来很简单,但我偶然发现了一些挣扎。我知道一些HTML和JavaScript,但我对jQuery和AJAX都是全新的。

到目前为止,我已设法使用.load()方法使用jQuery刷新图片ID,我也尝试使用.attr(),但它对我不起作用,我仍然必须刷新页面才能看到图像,即从客户端发送新请求。我想要的是服务器独立于客户端发送请求的天气在网页上进行更改。

我的代码现在看起来像这样:

    <head>
      <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    </head>
    <body>
      <div id="cofimages">
        <img id="images" src="0.jpg" />
      </div>
      <script>        
        $("#cofimages").load("index.html");
      </script>
    </body>

但现在的问题是图像加载速度非常慢,而客户端要求不断。 有什么方法可以用不同的方法解决这个问题吗?无论如何,我可以预加载图像,以便加载时间减少?任何建议/想法/解决方案都受到欢迎。

3 个答案:

答案 0 :(得分:0)

您可以使用它,但这取决于您想要如何触发更改

$(function(){
  $( "#images" ).load( "ajax/index.html #id_form_the_sended_html" );
});

答案 1 :(得分:0)

您可以显示所有图像:none,然后在需要时显示.show()和.hide()。

这个问题是访问网站时额外加载15张图片的时间。

答案 2 :(得分:0)

https://jsfiddle.net/d5tcq5av/

这就是你要找的东西。

var imageList = [
  "http://www.gstatic.com/webp/gallery/1.jpg",
  "http://www.gstatic.com/webp/gallery/2.jpg",
  "http://www.gstatic.com/webp/gallery/3.jpg",
  "http://www.gstatic.com/webp/gallery/4.jpg",
  "http://www.gstatic.com/webp/gallery/5.jpg",
  "http://www.gstatic.com/webp/gallery/6.jpg",
  "http://www.gstatic.com/webp/gallery/7.jpg",
  "http://www.gstatic.com/webp/gallery/8.jpg",
  "http://www.gstatic.com/webp/gallery/9.jpg"
]
var index = 0;

setInterval(function() {
  document.querySelector("#test").src = imageList[index];
  index++;
}, 5000)
<img id="test" src="" />