bootstrap中的等待值确认模态?

时间:2017-01-23 21:23:48

标签: 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>

和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);
    })
});

实际上,当用户按下按钮时会出现一个引导对话框,我只有在用户按下继续按钮.bnt-ok时才需要显示警告,但实际上我无法理解如何执行此操作。有人可以告诉我怎么样?感谢。

JSFIDDLE

更新

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

one: function()
{
    if(two()) //if function two return true then show alert
    {
        alert(true);
    }
}

2函数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;
 }

3问题来自函数two,&#39;因为在单击用户按钮之前无法停止该功能。因此显示确认对话框但函数返回true。我该如何等待用户点击?

2 个答案:

答案 0 :(得分:1)

只需将点击处理程序附加到.btn-ok元素。

因此:

$('.btn-ok').click(function(){
   alert(true);
});

jsFiddle

编辑:

使用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)
      });

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

答案 1 :(得分:0)

我很了解这个问题。 纯Typescript解决方案如下所示:

const result: boolean = confirm(message);
                if (result == true) {
                    return ConfirmationResult.ConfirmationResultPositive;
                } else {
                    return ConfirmationResult.ConfirmationResultNegative;
                }

其中ConfirmationResult.ConfirmationResultPositive是一些枚举。 交易确认功能将显示标准js窗口并等待用户结果(阻止进一步执行)。不幸的是,引导程序没有此标准功能。例如,WinForms,WPF和UMP(清除异步)具有相同的标准行为。 我还认为,使用Promise <>,我们可以使用bootstrap modal解决该问题。

相关问题