jQuery Dialog, closing when click outside

2019-07-27 06:24发布

I know I can 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?

4条回答
Summer. ? 凉城
2楼-- · 2019-07-27 07:00

From my tests, this is working well.

$('[data-role=dialog]').dialog( "close" );

It closes any dialog.

查看更多
Fickle 薄情
3楼-- · 2019-07-27 07:02

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");}) });  
查看更多
女痞
4楼-- · 2019-07-27 07:09

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");
            }
        );
    }
);
查看更多
霸刀☆藐视天下
5楼-- · 2019-07-27 07:17

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.

查看更多
登录 后发表回答