jQuery UI dialog - check if exists by instance method

孤者浪人 提交于 2019-11-30 04:10:06
jbabey

The latest version of jQuery UI no longer allows you to call UI methods on items that are not initialized yet. I've just been wrapping them in an if statement, like:

if ($("#divToBeDialoged").hasClass('ui-dialog-content')) {
    // do whatever
} else {
    // it is not initialized yet
}

Edit: changed class name, thanks @dmnc

Darwin Santos Arismendy

It is also a good habit to empty and destroy dialogs once you're done using them. I usually use this code in the close event of each dialog

$("#myDialog").dialog({
    // other options
    close: function(event, ui) {
        $(this).empty().dialog('destroy');
    }
}

That'd be my advice, rather than asking every time if a dialog exists in an instance make sure that each dialog cleans up after itself.

You can use:

if($('#id').is(':ui-dialog')) {
}

or

    var obj = $('<div>test</div>').dialog();
    if (obj.is(':ui-dialog')) {
      alert('I\'m a dialog')
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
xaviqv

If you are making that dialog from an existing id in your html code, like this example:

$('#main').dialog({});

Notice that dialog() adds the class ui-dialog in a <div> parent element generated for it to work. At the #main element, the classes added by dialog() are: ui-dialog-content and ui-widget-content (in jquery-ui-1.9.2). So, in this case, following the example from @jbabey, you can check the existing dialog doing:

if ($('#main').hasClass('ui-dialog-content')) {
    // do whatever
}
     if ($('#update').is(':data(dialog)')) 
     {
              //#update has dialog
     }
     else
     {
              //#update does't have dialog
     }

For jQuery UI - v1.10.3

if($( "#myDialog" ).is(':data(uiDialog)')){//is(':data(dialog)') does not work
    //Dialog exist
}

another way is

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