我使用的是Fotorama 4.5.0 (Rails gem),在获取API对象时遇到了问题。
在页面加载中,Fotorama位于隐藏的div中。它会在单击时以模式打开。
下面是代码( code ):
$objects = $('*[rel="fotorama"]')
$fotorama_div = $('.fotorama')
$fotorama_div
.on('fotorama:showend', (e, fotorama, extra) ->
// resizing fotorama
).fotorama()
fotorama = $fotorama_div.data('fotorama')
console.log(fotorama) // here is undefined
$objects.on 'click', ->
// finding index of an image
modal.open({content: $('#fotorama-container')})
fotorama.show(index) // index is ok使用此代码,fotorama对象始终为undefined。
好的,我添加了带有检查的if:
$objects = $('*[rel="fotorama"]')
$fotorama_div = $('.fotorama')
$fotorama_div
.on('fotorama:showend', (e, fotorama, extra) ->
// resizing fotorama
).fotorama()
fotorama = $fotorama_div.data('fotorama')
console.log(fotorama) // here is undefined
$objects.on 'click', ->
// finding index of an image
modal.open({content: $('#fotorama-container')})
if typeof fotorama == "undefined"
fotorama = $fotorama_div.data('fotorama')
console.log(fotorama) // here is undefined after the first click on object
fotorama.show(index) // index is ok在第一次单击object之后- fotorama仍然是undefined,但是在我关闭一个模式并进行第二次单击之后-我得到了fotorama object,一切都像预期的那样工作。
当我在控制台中执行$fotorama_div.data('fotorama')时,它可以工作。
如何在页面加载时获取fotorama对象?
发布于 2014-07-01 14:59:28
我遇到了完全相同的问题-在控制台中加载fotorama的div中给出了"undefined“,只是在再次显示div之后,fotorama对象才被正确加载。
我发现这是因为在一个带有"display: none;“css样式的对象中加载fotorama。我不知道为什么,但是如果fotorama加载了隐藏的东西,那么它就会崩溃。
我不知道任何RoR,但我的建议是首先显示模式,然后加载fotorama $fotorama_div.fotorama()后,模式是打开。
发布于 2020-12-14 00:30:19
我遇到了同样的问题,并找到了它返回undefined的原因。
如果$fotorama_div具有style="display: none;"属性,则$fotorama_div.data('fotorama')将返回undefined。
因此,解决方案是在运行$fotorama_div.data('fotorama')之前删除此属性style="display: none;"。
$fotorama_div.show().data('fotorama');如果仍然返回undefined,那么检查$fotorama_div的父类是否有display: none css。
let hiddenParents = $fotorama_div.parents().filter(function() {
return $(this).css('display') == 'none';
});
hiddenParents.show();
let fotorama = $fotorama_div.data('fotorama');
hiddenParents.hide();
// Now enjoy with your fotorama from here.https://stackoverflow.com/questions/23211016
复制相似问题