UI对话框模式窗口在第二次单击时用作模态窗口

时间:2012-02-20 02:32:19

标签: jquery-ui jquery dialog window modal-dialog

我遇到了Jquery UI对话框的问题,当我第一次单击该按钮时,它确实显示了对话框但没有显示模态对话框,但是当你第二次单击它时,它会正确显示为模态对话框

$('.ajax').live('click', function ()
{
    var url = "/home/test";
    var dialog = $("#dialog");

    $( "#dialog" ).dialog({
        height: 140,
        title:"Title",
        modal: true
    });


    if ($("#dialog").length == 0)
    {
        dialog = $('<div id="dialog"></div>').appendTo('body');
    }
    $.ajax(
        {
            url: url,
            beforeSend: function (jqXHR, settings)
            {
                //show an animated gif
            },
            complete: function (jqXHR, textStatus)
            {
                //hide the animated gif
            },
            success: function (data, textStatus, jqXHR)
            {
                dialog.dialog().html(data);
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                dialog.dialog().html("An error occured...");
            }
        });

    return false;
});

以下是按钮点击事件的代码

<button class="ajax">open dialog</button>

请参阅此链接以测试上述代码

http://jsfiddle.net/jRPfu/13/

1 个答案:

答案 0 :(得分:1)

我会这样做。

  1. 您声明变量dialog,因此请在之后使用

  2. 直接检查是否找到了dialog.length的#dialog元素。如果它为空,请创建标记

  3. 使用选项autoOpen: false初始化对话框。这样,对话框一劳永逸地初始化,但它将保持隐藏状态。

  4. 在您的ajax回调中,调用open方法以显示包含dialog.dialog('open')的对话框。作为旁注,设置对话框的内容然后打开它似乎更合乎逻辑。

  5. 进一步阅读:

    以下是修改后的代码:

    var dialog = $("#dialog");
    
    if (dialog.length == 0) {
    
        dialog = $('<div id="dialog"></div>').appendTo('body');
    
        dialog.dialog({
            height: 140,
            title: "Title",
            modal: true,
            autoOpen: false
        });
    
    }
    
    $.ajax({
        url: url,
        ...
        success: function(data, textStatus, jqXHR) {
            dialog.html(data).dialog('open');
        },
        error: function(jqXHR, textStatus, errorThrown) {
            dialog.html("An error occured...").dialog('open');
        }
    });
    

    <强> DEMO

相关问题