引导程序中的等待值确认模式?

Aga*_*nMe 3 javascript jquery twitter-bootstrap

这个问题似乎很愚蠢,但我不知道如何等待确认按钮返回一个值。Javascript 基于单线程,所以我需要知道如何设置回调函数之类的东西,直到按下按钮,这是对话框的结构:

<div class="modal fade" id="confirmation" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Confirm</h4>
            </div>
            <div class="modal-body">
                <label>Are you sure?</label>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default btn-ok" data-dismiss="modal">Continue</button>
                <a class="btn btn-danger" data-dismiss="modal">Cancel
                </a>
            </div>
        </div>
    </div>
</div>

<button id="go">press me</button>
Run Code Online (Sandbox Code Playgroud)

和js:

$(document).ready(function()
{
    $('#go').click(function()
    {
        $('#confirmation').modal('show');
        //if the user has pressed the .btn-ok button then an alert appear
        alert(true);
    })
});
Run Code Online (Sandbox Code Playgroud)

实际上,当用户按下按钮时会出现引导对话框,只有当用户按下继续按钮时.bnt-ok,我才需要显示警报,但实际上我不明白如何执行此操作。有人可以告诉我怎么做吗?谢谢。

JSFIDDLE

更新

1 用户触发事件并one执行函数:

one: function()
{
    if(two()) //if function two return true then show alert
    {
        alert(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

2 函数二显示引导对话框:

 two: function()
 {
    $('#confirmation').show();

   //here I need to check if the user has pressed btn-ok, if yes,
   //I need to return true, otherwise false

   return true;
 }
Run Code Online (Sandbox Code Playgroud)

3 问题出在函数上two,因为在用户单击按钮之前无法停止该函数。所以显示确认对话框,但函数返回true。如何等待用户点击?

Ada*_*ski 5

简单地,将单击处理程序附加到.btn-ok元素。

像这样:

$('.btn-ok').click(function(){
   alert(true);
});
Run Code Online (Sandbox Code Playgroud)

js小提琴

编辑:

使用 ES6 承诺检查您的问题的解决方案。

const modal = new Promise(function(resolve, reject){
       $('#confirmation').modal('show');
       $('#confirmation .btn-ok').click(function(){
           resolve("user clicked");
       });
       $('#confirmation .btn-danger').click(function(){
           reject("user clicked cancel");
       });
      }).then(function(val){
        //val is your returned value. argument called with resolve.
        alert(val);
      }).catch(function(err){
        //user clicked cancel
        console.log("user clicked cancel", err)
      });
Run Code Online (Sandbox Code Playgroud)

更新了 jsFiddle。请注意,它使用ES6 promises,您应该检查浏览器支持或转译您的代码(例如使用 babel)。

  • @AgainMe 不确定你的意思 (2认同)