jQuery Dialog, closing when click outside

…衆ロ難τιáo~ 提交于 2019-12-11 12:48:12

问题


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?


回答1:


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");}) });  



回答2:


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");
            }
        );
    }
);



回答3:


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.




回答4:


From my tests, this is working well.

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

It closes any dialog.



来源:https://stackoverflow.com/questions/3351854/jquery-dialog-closing-when-click-outside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!