0

我写了一个函数confirmMessage(msg)来处理链接的 onclick 事件:

<a href="delete.php?id=12" onclick="return confirmMessage('Are You REALLY Sure?')">Delete</a>

该函数的代码是:

<script>
    function confirmMessage(msg){
    p = true
    elementHtml = '<div id="ConfirmMessage">'+msg+'</div>';
    $("body").append(elementHtml);
    $("#ConfirmMessage").dialog({
      resizable: false,
      height:140,
      modal: true,
      buttons: {
        "Delete": function() {
        p = true;           
          $( this ).dialog( "close" );

        },
        Cancel: function() {
        p = false;
          $( this ).dialog( "close" );

        }
      }
    }

    );

    return p;

}

    </script>

在上面的函数中,我将变量设置p为案例容器,即 true 或 false,最初我将其设置为 true。此外,消息元素是动态创建的。但是,当我单击删除链接时,它不会等到我决定删除或取消并删除它。

当我p最初设置为假时,它不会执行任何其他关闭对话框的决定。

这段代码哪里出错了?!

4

3 回答 3

2

您的错误在于认为该功能会在返回之前等待您单击其中一个按钮。.dialog()显示对话框并立即返回。响应用户交互必须在回调函数中完成。

close:关闭对话框时使用处理程序运行代码:

$("#ConfirmMessage").dialog({
  resizable: false,
  height:140,
  modal: true,
  close: function() {
    if (p) {
        ...
    } else {
        ...
    }
  },
  buttons: {
    "Delete": function() {
    p = true;           
      $( this ).dialog( "close" );

    },
    Cancel: function() {
    p = false;
      $( this ).dialog( "close" );

    }
  }
}

);
于 2013-10-10T23:10:27.720 回答
2

jQuery 对话框异步——它不会阻塞。该函数将继续执行并返回,而无需等待响应。您将需要使用以下代码:

function confirmMessage(msg,goto){
    elementHtml = '<div id="ConfirmMessage">'+msg+'</div>';
    $("body").append(elementHtml);
    $("#ConfirmMessage").dialog({
        resizable: false,
        height:140,
        modal: true,
        buttons: {
            "Delete": function() {   
                 $( this ).dialog( "close" );
                 window.location.href=goto;
             },
             Cancel: function() {
                 $( this ).dialog( "close" );
             },
         },
     });
    return false;
}

和:

<a href="delete.php?id=12" onclick="return confirmMessage('Are You REALLY Sure?',this.href)">Delete</a>

改变所以回报并不是真正决定会发生什么。

请参阅此JSFiddle

于 2013-10-10T23:55:35.297 回答
0

在您甚至能够看到模态窗口之前执行“return p”。您的对话框方法是异步执行的

于 2013-10-10T23:11:55.040 回答