使用Twitter Bootstrap模态框替代确认对话框

9
我将使用 Twitter Bootstrap 模态框来代替自定义确认对话框。
我的函数:
function getConfirm(confirmMessage){
    if ( confirmMessage == undefined){
        confirmMessage = '';
    }
    $('#confirmbox').modal({
    show:true,
        backdrop:false,
        keyboard: false,
    });

    $('#confirmMessage').html(confirmMessage);
    $('#confirmFalse').click(function(){
        $('#confirmbox').modal('hide');
        return false;
    });
    $('#confirmTrue').click(function(){
        $('#confirmbox').modal('hide');
        return true;
    });
}   
</script>
<div class="modal" id="confirmbox" style="display: none">
    <div class="modal-body">
        <p id="confirmMessage">Any confirmation message?</p>
    </div>
    <div class="modal-footer">
        <button class="btn" id="confirmFalse">Cancel</button>
        <button class="btn btn-primary" id="confirmTrue">OK</button>
    </div>
</div>

调用函数

var confimChange=getConfirm("Do You confirm?");
if(confimChange){
    alert('perfect you confirmed')
}else{
    alert('why didnt you confirmed??')
}

问题在于getConfirm函数没有返回true或false。


可行代码:

if(receiverListCount > 0){
    var confimChange=confirm("Message");
    if(confimChange){
        resetReceiverList();
    }else{
        return false;
    }
}

经过修改和更改后的代码片段/无法工作

if(activeDiv == '#upload'){
    if(listOfSelectedGroups.length> 0|| receiverListCount > 0){
        getConfirm("message",function(result){
            if(result){
                resetReceiverList();
            }else{
                return false;
            }
        });
    }
}

最终我决定使用bootboxjs

1个回答

22

你的方法是错误的,它会以异步方式执行,所以在返回之前不会等待模态对话框关闭。尝试像这样:

function getConfirm(confirmMessage,callback){
    confirmMessage = confirmMessage || '';

    $('#confirmbox').modal({show:true,
                            backdrop:false,
                            keyboard: false,
    });

    $('#confirmMessage').html(confirmMessage);
    $('#confirmFalse').click(function(){
        $('#confirmbox').modal('hide');
        if (callback) callback(false);

    });
    $('#confirmTrue').click(function(){
        $('#confirmbox').modal('hide');
        if (callback) callback(true);
    });
}  

getConfirm('Are you sure?',function(result) {
   // Do something with result...
});

注意,你只需要初始化模态框一次并且挂上事件。我会给模态框主体设置一个ID,在显示前简单地更改内容即可。

你还应该将背景设置为true,这样可以在用户确认之前防止其访问页面。


它运行良好,但我的函数没有等待getConfirm函数。 - Ayhan
惊人的解决方案。谢谢! - Houman
6
好的解决方案,但在多次调用后会表现不一致,因为分配给按钮的回调没有被移除,它们都将在N次调用后被评估。如果您没有附加其他事件,那么像以下这样的内容就足够了:$('#confirmFalse').off().click(function(){ - Eddie Jamsession

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