检查jQuery“Fancybox”是否已经注册?

我正在重新编写一个像这样的jQuery fancybox:

$(document).ready(function() { $("#help").fancybox({ 'width': '90%', 'height': '90%', 'autoScale': true, 'transitionIn': 'elastic', 'transitionOut': 'none', 'titleShow': false, 'type': 'iframe' }); }); 

但是,在页面传输/回发时,它会多次注册,这会减慢到破坏的程度。 有没有办法检查事件是否已经注册,如果没有,请注册?

伪代码:

  //check if fancybox has not been registered if($("help").fancybox == null)) { //register fancy box } 

当fancybox运行时,它会在jQuery的data对象中添加一个fancybox条目。

您可以测试它的存在:

 if( ! $("#help").data().fancybox ) { //register fancy box } 

Fancybox使用$(element).data()来存储其元素相关配置。 你只需要检查是否存在fancybox

 $("#fancy").data("fancybox"); 

看到这个小提琴更多fnu。

此函数查找您的#help元素,并仅在fancybox.js存在时才加载它。 成功加载Fancybox.js后,它将调用success函数并初始化你的fancybox。

这只会影响具有元素#help页面。 因此,您可以节省HTTP请求和带宽。

请参阅: http : //api.jquery.com/jQuery.ajax/

您还应该查找允许您处理错误的error function

 $(document).ready(function() { // Look for #help if ( $('#help').html() !== null ) { // Load, init and config the fancybox $.ajax({ url: '/js/path/to/fancybox.js', type: 'GET', dataType: 'script', success: function() { // Init Fancybox $("#help").fancybox({ 'width': '90%', 'height': '90%', 'autoScale': true, 'transitionIn': 'elastic', 'transitionOut': 'none', 'titleShow': false, 'type': 'iframe' }); } }); } }); 

有点晚了,但对于Fancybox 2,我使用:

 parent.jQuery.fancybox.isOpen 

我认为你也可以使用:

parent.jQuery.fancybox.isOpened

如果在网站上打开fancybox,则两个语句都将返回true。