jQuery Dialog, closing when click outside
I know I can开发者_如何学Go use the following to close the dialog box by clicking outside:
$('.ui-widget-overlay').click(function() { $("#dialog").dialog("close"); });
But how do I change this so it works for every dialog box, ie I want to say close any dialog box as we have multiple on a page and would be easier to have one line of code?
you can give each dialog a class
and then select it and run on each and cose it even if its not open it will work:
$('.ui-widget-overlay').click(function() { $(".dialogs").each(function()
{$(this).dialog("close");}) });
Maybe this is overkill, but try
$('.ui-widget-overlay').live('click',
function() {
$(".ui-dialog").dialog("close");
}
);
You only need to run this code once on your page, the live
method should make it work any time you open a dialog.
EDIT: If this isn't working, it might be .dialog
's fault. Try
$('.ui-widget-overlay').live('click',
function() {
$(".ui-dialog").each(
function() {
$(this).dialog("close");
}
);
}
);
The answers given almost work. Except you can't call the dialog('close')
on elements with the ui-dialog
class. That is the jquery-ui generated content around your original element and the close must be called on the original element you used when you called .dialog
. Fortunately jquery adds a ui-dialog-content
class to them. Use that to modify Guy's solution and you get:
$(document).on('click', '.ui-widget-overlay', function() {
$('.ui-dialog-content').each(function() {
$(this).dialog('close');
});
});
You can try it out for yourself over on jsfiddle.
EDIT: Changed .click
to .live
since the ui-widget-overlay
may not exist yet when this code is executed.
EDIT: Changed to .on
instead of .live
since it is depreciated.
From my tests, this is working well.
$('[data-role=dialog]').dialog( "close" );
It closes any dialog.
精彩评论