为什么我的模态jQuery对话框多次打开?

时间:2011-05-25 09:15:16

标签: javascript jquery jquery-ui

我想使用jQuery对话框在模态对话框中打开答案表单。加载页面后,这是第一次,没关系,但在每次点击后,它将打开2^n-1次! (n是点击次数)

类似的东西:

  

点进>打开对话框(1次) - >关闭对话框

     

点进>打开对话框(2次) - >关闭对话框

     

点进>打开对话框(4次) - >关闭对话框

     

点进>打开对话框(8次) - >关闭对话框

这是代码:

$(function () {
    $('label.answer').click(function (event) { openInDialog(this, event, 'http://localhost/Questions/Answer/2') });
});

function openInDialog(element, event, target) 
{
    event.preventDefault();
    var $loading = $('<img src="../../Others/images/ajaxLoading.gif" alt="loading" class="ui-loading-icon">');
    var $url = target;    
    var $title = "Title"; 
    var $dialog = $('<div></div>');
    $dialog.empty();


    $dialog
            .append($loading)
            .load($url)
            .dialog(
            {
                autoOpen: false
                , title: $title
                , modal: true
                , show: 'fade'
                , hide: 'fade'
            });

    $dialog.dialog('open');
};

1 个答案:

答案 0 :(得分:4)

初始化函数外部的对话框。在加载成功之前,您也不应尝试打开对话框。

$(function () {
    $('label.answer').click(function (event) { openInDialog(this, event, 'http://localhost/Questions/Answer/2') });
});
var $dialog = $('<div></div>').dialog(
{
    autoOpen: false
    , modal: true
    , show: 'fade'
    , hide: 'fade'
});

function openInDialog(element, event, target)
{
    event.preventDefault();
    var $loading = $('<img src="../../Others/images/ajaxLoading.gif" alt="loading" class="ui-loading-icon">');
    var $url = target;
    var $title = "Title"; 
    $dialog.empty();
    /* this is incorrect $dialog.dialog({ "option", "title",$title})*/
    $dialog.dialog("option", "title",$title)
    .append($loading)
    .load($url,function(){
        $dialog.dialog('open');
    });
};