开发者

How would I reference a dynamically created jQuery dialog box so I can close it programatically?

When I began using jQuery a little over a year ago, I needed to load remote content into a pop-up dialog box. After scouring the internet and trying out several suggested methods for doing this, I came upon a function that worked exactly as I needed it to. However, one problem I've never solved is how to reference the dynamic dialog box so it can be closed from an outside function.

Here's the function that creates the dialog box, appends it to the body, and then loads a page into it:

function openDynamicDialog() {
  var url = 'mypage.cfm';
  var dialog = $('`<div style="display:hidden"></div>`').appendTo('body');
    $(dialog).dialog({
      autoOpen: true,
      title: 'My Title',
      resizable: true,
      modal: true,
      width: 250,
      height: 100,
      close: function(ev, ui) {
             $(this).remove(); // ensures any form variables are reset.
           }, 
      buttons: {
        "Close": function(){ 
          $(this).dialog("close");
        }
      }
  });
  // load remote content
  dialog.load(
    url,
    {},
    function (responseText, textStatus, XMLHttpRequest) {
      dialog.dialog();
     }
  );
  //prevent the browser from following the link
  return false; };

I've considered giving that hidden div a hard-coded id value, but I'm not sure if there are drawbacks to that approach.

Any suggestions would be开发者_开发知识库 most appreciated.


I would use a hard-coded id value for the <div> element.


No there shouldn't be any drawback giving it an ID. If you fear of some kind of conflicts then you can give it a class instead, or save a reference to the div object in a global variable.


Well im not sure what the return false is at the end. so if you don't need that, do this:

function openDynamicDialog() {
    var url = 'mypage.cfm';
    var dialog = $('<div>').css('display','none').appendTo('body');
    $(dialog).dialog({
        autoOpen: true,
        title: 'My Title',
        resizable: true,
        modal: true,
        width: 250,
        height: 100,
        close: function(ev, ui) {
            $(this).remove(); // ensures any form variables are reset.
        },
        buttons: {
            "Close": function() {
                $(this).dialog("close");
            }
        }
    });
    // load remote content
    dialog.load(
    url, {}, function(responseText, textStatus, XMLHttpRequest) {
        dialog.dialog();
    });

    return dialog;
}

//call it like this:
var dialog = openDynamicDialog();
//..code
//close it:
dialog.dialog('close');

OR

if you still need that return false, you can do this on the var dialog line of the function:

var dialog = $('<div>', {id: 'dialog_id'}).css('display','none').appendTo('body');

and then reference it from the outside:

var dialog = $('#dialog_id');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜