我如何引用动态创建的jQuery对话框,以便以编程方式关闭它?

时间:2011-05-02 21:03:22

标签: jquery-ui modal-dialog

当我在一年多前开始使用jQuery时,我需要将远程内容加载到弹出对话框中。在搜索了互联网并尝试了几种建议的方法之后,我发现了一个功能完全按照我的需要工作。但是,我从未解决的一个问题是如何引用动态对话框,以便可以从外部函数关闭它。

这是创建对话框的函数,将其附加到正文,然后将页面加载到其中:

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

我考虑过给隐藏的div一个硬编码的id值,但我不确定这种方法是否存在缺陷。

任何建议都会受到最高的赞赏。

3 个答案:

答案 0 :(得分:0)

我不确定return false到底是什么。因此,如果您不需要,请执行以下操作:

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');

如果您仍然需要return false,则可以在该功能的var dialog行执行此操作:

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

然后从外面引用它:

var dialog = $('#dialog_id');

答案 1 :(得分:0)

不应该给它一个ID的任何缺点。如果您担心某种冲突,那么您可以改为给它一个类,或者在全局变量中保存对div对象的引用。

答案 2 :(得分:0)

我会为<div>元素使用硬编码的id值。