检测 jQueryUI 对话框是否打开

我使用的是 jQueryUI 对话框。如果它是开放的,我想做一件事。如果关门了,我想再做一次。

我的问题是,如何检测 jQueryUI 对话框是否打开?

110617 次浏览

If you want to check if the dialog's open on a particular element you can do this:

if ($('#elem').closest('.ui-dialog').is(':visible')) {
// do something
}

Or if you just want to check if the element itself is visible you can do:

if ($('#elem').is(':visible')) {
// do something
}

Or...

if ($('#elem:visible').length) {
// do something
}

If you read the docs.

$('#mydialog').dialog('isOpen')

This method returns a Boolean (true or false), not a jQuery object.

Actually, you have to explicitly compare it to true. If the dialog doesn't exist yet, it will not return false (as you would expect), it will return a DOM object.

if ($('#mydialog').dialog('isOpen') === true) {
// true
} else {
// false
}

jQuery dialog has an isOpen property that can be used to check if a jQuery dialog is open or not.

You can see example at this link: http://www.codegateway.com/2012/02/detect-if-jquery-dialog-box-is-open.html

Nick Craver's comment is the simplest to avoid the error that occurs if the dialog has not yet been defined:

if ($('#elem').is(':visible')) {
// do something
}

You should set visibility in your CSS first though, using simply:

#elem { display: none; }