jQueryUI对话框替换确认?

时间:2016-08-02 14:09:34

标签: javascript jquery html jquery-ui

我试图用jQueryUI对话框覆盖默认确认框,这是我的尝试:

window.confirm = function (message_confirm) {
        $(document.createElement('div'))
            .attr({ title: 'Please confirm', 'class': 'confirm', 'id': 'dialogconfirm' })
            .html(message_confirm)
            .dialog({
                buttons: { YES: function () { return true; }, NO: function () { $(this).dialog('close'); } },
                close: function () { $(this).remove(); },
                draggable: true,
                modal: true,
                resizable: false,
                width: 'auto',
                hide: { effect: "fade", duration: 300 },

            });

    };

这适用于运行此脚本后,调用常规confirm会显示jQueryUI对话框,但YES选项不起作用。我有一个像下面这样的ajax调用:

if (confirm("Are you sure you want to delete this user?"))
{
      alert("test");
     //ajax call
}
return false;

并没有出现测试警报。对话框的NO选择工作正常。如何让YES工作?

谢谢。

3 个答案:

答案 0 :(得分:5)

你可以在函数

中添加一个回调参数
window.confirm = function (message_confirm, ok_callback)

点亮是

 buttons: { YES: function () { ok_callback(); }}

然后再继续

confirm("message", function(){
    alert('smth');
});

答案 1 :(得分:4)

因为对话框是异步的,所以您可以使用延迟方法:

window.confirm = function (message_confirm) {
  var defer = $.Deferred();
  $('<div/>', {title: 'Please confirm', 'class': 'confirm', 'id': 'dialogconfirm', text: message_confirm})
  .dialog({
    buttons: {
      YES: function () {
        defer.resolve("yes");
        $(this).attr('yesno', true);
        $(this).dialog('close');
      }, NO: function () {
        defer.resolve("no");
        $(this).attr('yesno', false);
        $(this).dialog('close');
      }
    },
    close: function () {
      if ($(this).attr('yesno') === undefined) {
          defer.resolve("no");
      }
      $(this).remove();
    },
    draggable: true,
    modal: true,
    resizable: false,
    width: 'auto',
    hide: {effect: "fade", duration: 300}
  });
  return defer.promise();
};

$(function () {
  confirm("Are you sure you want to delete this user?").then(function(yesno) {
    console.log(yesno);
  });
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

答案 2 :(得分:1)

尝试以下内容。它对我有用。

 <script>
  $( function() {
    $( "#dialog-confirm" ).dialog({
      resizable: false,
      height: "auto",
      width: 400,
      modal: true,
      buttons: {
        "Delete user": function() {
          alert("test");
        },
        Cancel: function() {
          $( this ).dialog( "close" );
        }
      }
    });
  } );
  </script>
</head>
<body>

<div id="dialog-confirm" title="Please confirm">
  <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>Are you sure you want to delete this user?</p>
</div>