在jQuery中创建确认对话框

3
$("#first").dialog({ width: 304, modal: true,

  beforeclose: function (e, ui) 
  {
        $("#confirm").dialog({ width: 500, modal: true,
            buttons: {
                "Confirm": function () {
                    document.location.href = "/Home/Index";
                },
                "Cancel": function () {
                    $(this).dialog('close');
                    return false;
                }
            }
        });
    }
});

对话框#first在等待对话框#confirm打开之前就关闭了。我知道javascript的confirm()函数,但我想在这种情况下使用对话框。我该怎么做?
2个回答

8

根据精细手册

beforeClose(event, ui)

当对话框即将关闭时触发。如果取消,则对话框不会关闭。

因此,您希望将beforeClose处理程序设置为return false,以防止对话框关闭:

beforeClose: function(e, ui) {
    $("#confirm").dialog({ width: 500, modal: true, /* ... */ });
    return false;
}

您的确定按钮会更改位置,因此您不必担心beforeClose处理程序会阻止第二个对话框关闭第一个对话框。如果您没有更改页面位置,则需要某种标志来防止beforeClose阻止所有关闭;例如:

beforeclose: function(e, ui) {
     var $dlg = $(this);
     if($dlg.data('can-close')) {
         $dlg.removeData('can-close');
         return true;
     }
     $("#confirm").dialog({
         //...
         buttons: {
             Confirm: function() {
                 $(this).dialog('close');
                 $dlg.data('can-close', true);
                 $dlg.dialog('close');
             },
             Cancel: function() {
                 $(this).dialog('close');
             }
         }
     });
     return false;
 }

Demo: http://jsfiddle.net/ambiguous/jYZpD/


3

我将回答自己的问题,这个方案运行良好:

$("#first").dialog({ width: 304, modal: true,

  beforeclose: function (e, ui) 
  {
        $("#confirm").dialog({ width: 500, modal: true,
            buttons: {
                "Confirm": function () {
                    document.location.href = "/Home/Index";
                },
                "Cancel": function () {
                    $(this).dialog('close');
                }
            }
        });
      return false;
    }
});

是的,@muistooshort +1,这是真的。 - Gaurav
说明:首先创建并显示对话框。当您尝试关闭它时,beforeClose事件将被触发。在beforeClose事件的处理程序中,您会显示一个辅助的“确认”对话框,然后返回false值,这将防止第一个对话框关闭。当您单击标记为“确认”的按钮时,您手动导航到/home/index。当您单击取消时,您手动关闭确认模态。 - deadbabykitten

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接