且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

元素加载时jQuery加载图像

更新时间:2023-12-05 16:37:04

根据您要尝试执行的操作,并不是特别困难.下面将显示一个加载图像(预先存在),然后加载通过ajax检索的一些html,然后在完成后将隐藏该加载图像.

Depending on what you are trying to do, it's not particularly hard. The following will show a loading image (pre-existing), then load some html retrieved via ajax, then upon completion, it will hide the loading image.

$(function() {
   $('#activate').click( function() {
      $('#loadingImg').show();
      $('#whereItGoes').load( 'url-to-data-to-be-loaded', function() {
          $('#loadingImg').hide();
      });
   });
});

如果要加载的数据是图像,则它会变得有些棘手,因为可以在实际下载图像数据之前调用加载回调.在这种情况下,一种策略是使HTML包含一个脚本,该脚本知道要加载多少个图像,并具有一个onloaded事件处理程序,该事件处理程序基本上会剔除图像计数,直到下载完所有图像为止.我通常将它与超时结合起来,以防在图像数据可用之前未添加onloaded处理程序(在这种情况下将不会触发).

If the data to be loaded are images, then it gets a little tricker since the load callback may be called before the image data is actually downloaded. One strategy in that case is to have a script included with the HTML that knows how many images are to be loaded and have an onloaded event handler that basically ticks off the image count until all the images have been downloaded. I usually couple it with a timeout in case the onloaded handler doesn't get added before the image data is available (in which case it won't fire).