问题
I have a function that gets executed when clicking on certain things within the content of my fancybox. The functions work fine, but I cannot, for the life of me, figure out how to close fancybox programmatically. I have tried:
$.fancybox.close()
and parent.$.fancybox.close();
I have even tried triggering a click
to the close button but that has not worked either.
When I try $.fancybox.close()
I get
Uncaught TypeError: Cannot call method 'close' of undefined
Here is what my fancybox call looks like:
<a href="#display" class="fancybox" id="query" style="text-decoration:none; color:#000;" title="" data-fancybox-width="950">Open</a>
Here is what my function looks like (attached to the parent page's head)
$(document).on('click', ".group_box", function(e){
var nodeName = e.target.nodeName
//validation to ensure an input button was not pressed
if (nodeName != "INPUT"){
$.fancybox.close();
}
Any help greatly appreciated
回答1:
I think you have two options :
1). Create a close button (with an <a>
tag) and pass the $.fancybox.close()
method directly into its href
attribute like "
<a class="closeFancybox1" href="javascript:jQuery.fancybox.close()">close option 1</a>
This link can be added by your ajax call inside the #display
div
or you can append it to the fancybox content after show.
2). Create a close button using a unique selector and bind a click
event to it to trigger the $.fancybox.close()
method only until is visible inside fancybox
so having this html inside your fancybox content
<a class="closeFancybox2" href="javascript:;">close option 2</a>
bind a click
event to it to trigger the $.fancybox.close()
method using the afterShow
callback like
afterShow: function () {
$(".fancybox-inner").on("click", ".closeFancybox2", function () {
$.fancybox.close();
});
}
Notice we still used .on()
in its delegated form.
see JSFIDDLE using both options.
来源:https://stackoverflow.com/questions/21004046/close-fancybox-from-jquery