在Firebase中加载数据时运行JQuery

我有一个问题,我需要先从Firebase数据库获取图像链接然后我调用一个JQuery代码,将以一种美丽的方式组织图像>>但似乎Jquery运行之前我得到的图像,请帮助..!

JSfunction

new Firebase("https://zoominp.firebaseio.com/photos/"+imageID) .once('value', function(snap) { link = snap.child('imageLink').val(); link = 'images/'+link; var id = "img"; div.innerHTML += "HHHH"; }); 

JQuery的

 jQuery("#gallery").unitegallery( { tiles_type:"nested", tiles_nested_optimal_tile_width:200 }); 

Firebase异步加载(和同步)数据。 所以你拥有的jQuery代码确实会在数据从服务器返回之前执行。

要解决此问题,请将jQuery代码移动到Firebase回调中:

 var ref = new Firebase("https://zoominp.firebaseio.com/photos/"+imageID); ref.on('value', function(snap) { link=snap.child('imageLink').val(); link='images/'+link; var id="img"; div.innerHTML = div.innerHTML +"HHHH"; jQuery("#gallery").unitegallery({ tiles_type:"nested", tiles_nested_optimal_tile_width:200 }); }); 

我也将once()更改为on() 。 通过这种微小的更改,只要数据库中的数据发生更改,您的HTML就会更新。 尝试更改数据,您将体验Firebase的“神奇”。

由于异步加载在您第一次遇到它时难以绕过,我强烈建议您阅读这些问题的更深入的答案:

  • 如何从异步调用返回响应?
  • 为什么我的变量在函数内部修改后没有变化? – 异步代码引用
  • 处理函数中的异步调用(Firebase)
  • 从jQuery函数返回值

我从来没有使用Firebase,但是你需要在运行jQuery之前准备好你的实际资源 – 你不能以同步的方式做到这一点,因为当你调用你的jquery unitedGallery它会在.once('value')之前被.once('value')事件触发器。

你是否将这个new Firebase(....称为new Firebase(....在循环中更多次new Firebase(....或者其他什么东西?你可以做一些事情,比如保留关于是否将所有图像加载到数组中的信息。就像这样:让我们假设,你的图像存储在一个数组allOfYourImages 。然后,

像这样定义一个全局变量

 var images_loaded=[]; for(var i=0; i 

然后我假设你以某种方式迭代你的图片,因为你使用imageID 。 添加一个递增变量var image_number=0; 在迭代器之前,在每次图像迭代后执行image_number++ 。 喜欢

 var image_number=0; ...iteratorofyourchoiseihavenoideawhatareyouusing...{ new Firebase("https://zoominp.firebaseio.com/photos/"+imageID).once('value', function(snap){ ...DOM stuff previously did ... images_loaded[image_number]=true; checkAllImagesLoaded(); }); image_number++; } 

注意checkAllImagesLoaded()函数。 这将看看是否已经加载了所有图像并触发jQuery图库的东西,就像这样

 checkAllImagesLoaded(){ var all_loaded=true; for(var i=0; i