当我编码window.confirm自己时,如何返回true或false

时间:2016-04-22 08:10:21

标签: javascript

代码:

 (function (proxied) {
    window.confirm = function (msg) {
        noty({
            text: '<i class="fa fa-exclamation-triangle">'+msg+'</i>',
            theme: 'relax',
            dismissQueue: true,
            layout: 'center',
            buttons: [
                {
                    addClass: 'btn btn-success btn-circle', text: '<i class="fa fa-check"></i>', onClick: function ($noty) {
                        $noty.close();
                        return true;
                    }
                },
                {
                    addClass: 'btn btn-danger btn-circle', text: '<i class="fa fa-times"></i>', onClick: function ($noty) {
                        $noty.close();
                        return false;
                    }
                }
            ]
        });
        //return proxied.apply(this, arguments);
    };
})(window.confirm);

它无法正确返回true或false,我猜它可能是按钮关闭?谢谢大家。

1 个答案:

答案 0 :(得分:1)

只有本机对话框函数可以暂停JavaScript执行,直到采取某些操作,这意味着您将无法返回任何内容。您将不得不使用回调:

(function (proxied) {
    window.confirm = function (msg, callback) {
        noty({
            text: '<i class="fa fa-exclamation-triangle">'+msg+'</i>',
            theme: 'relax',
            dismissQueue: true,
            layout: 'center',
            buttons: [
                {
                    addClass: 'btn btn-success btn-circle', text: '<i class="fa fa-check"></i>', onClick: function ($noty) {
                        $noty.close();
                        callback(true);
                    }
                },
                {
                    addClass: 'btn btn-danger btn-circle', text: '<i class="fa fa-times"></i>', onClick: function ($noty) {
                        $noty.close();
                        callback(false);
                    }
                }
            ]
        });
        //return proxied.apply(this, arguments);
    };
})(window.confirm);

要使用您的功能,您必须这样做:

window.confirm("Do you want ice cream?", function(result){
    if(result){
        // The user wants ice cream
    }
});