繁体   English   中英

每秒在div中加载图片

[英]Loading image in div every second

我想以固定的时间间隔将图片加载到div中,例如每秒或两秒

我做了一些愚蠢的尝试

$(document).ready(function() {
  setTimeout('LoadImages()',100 );
});
function LoadImages()
{
   $('#Images').load('get_image.htm'); // get_image.htm displays image
}
</script>
<body>
<div id="Images"><div>

我知道这都是错误的,但是要使它正常工作需要做什么?

您需要setInterval而不是setTimeout

$(function() {
 var i = window.setInterval(function(){
    $('#Images').load('get_image.htm');
 },1000 );
});

您可以随时通过以下方式停止重新加载

clearInterval(i);

这样就可以了

$(document).ready(function() {
  setInterval(function() {
    $('#Images').load('get_image.htm'); // get_image.htm displays image
  },100 );
});

使用setInterval(),您可以在指定的毫秒数(本例中为100)后重复执行一个函数

避免在setTimeout / Interval中使用字符串,只需尝试一下

$(document).ready(function() {
  var div = $('#Images');
  setInterval(function() {
    div.load('get_image.htm'); // get_image.htm displays image
  }, 1000);
});

如果您需要每秒打一次电话,则延迟必须为1000 (而不是100),否则您的服务器将收到600 reqs / min而不是60。

还要创建对该节点的外部作用域引用,这样您就不会在每次函数调用时都重新评估$('#Images')

$(document).ready(function() {

   function LoadImages() {

     setTimeout(function() {
        $('#Images').load('get_image.htm'); // get_image.htm displays image
        LoadImages(); // recursive call to LoadImages
     }, 1000)

   }
});

如果要在完成图像加载后调用LoadImages() ,则

$(document).ready(function() {

   function LoadImages() {

     setTimeout(function() {
        $('#Images').load('get_image.htm', function() {

             LoadImages(); // recursive call to LoadImages

       }); // get_image.htm displays image

     }, 1000)

   }
});

如果需要每秒,请使用setInterval,并且1000ms是1秒。

$(document).ready(function() {
  setInterval('LoadImages',1000 );
});

setTimeout('LoadImages()',100 )应该类似于setTimeout(LoadImages,1000 ); setTimeout接受间隔参数,以millisecond为1秒。 要每秒执行一次,您应该使用setIntervalsetInterval(LoadImages,1000) setTiemout将仅运行一次。

因为setTimeout接受函数引用,因此使用'LoadImages()'将触发eval并立即执行函数并返回null。

您还应该使用append而不是一次又一次地将图像加载到该div中,这将替换所有先前的图像。 我不确定您是否有意这样做。

$(function() {
 var i = window.setInterval(function(){
    $('#Images').load('get_image.htm');
 },1000 );
});
function LoadImages()
{
 $.get('get_image.htm',function(data){
    $('#Images').append(data);
 });
}

暂无
暂无

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

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