jquery JavaScript Alertify with return from confirm

qmelpv7a  于 2023-06-22  发布在  jQuery
关注(0)|答案(2)|浏览(117)

我尝试使用alertify.js作为所有确认脚本的确认对话框。但是它并不像普通的JS confirm那样工作。在下面的代码中,我从未得到return true

function aConf ( mes ) {
    alertify.confirm( mes, function (e) {
        return e;
    });
}

<a href="#" onclick="if(aConf(\'Are you sure you wish to remove this?\')) { function(); } return false;">Delete</a>

当然,如果我用JS的confirm替换aConf,它就可以工作了。那么为什么alertify不把它的结果发送给我呢?

bz4sfanl

bz4sfanl1#

因为confirm是一个阻塞函数(在它返回true/false之前,JavaScript不会运行),而alertify是非阻塞的(JS会继续执行)。Alertify不会立即返回true/false,而是可能会立即返回undefined,然后在用户单击OK或Cancel后调用回调函数。该回调函数的返回值在您的示例中没有任何影响,因为onclick代码已经完成运行(因为它是非阻塞的)。
假设你正在使用这个:https://github.com/fabien-d/alertify.js/
这是它实际上如何使用回调函数,而不是返回值:

alertify.confirm( message, function (e) {
    if (e) {
        //after clicking OK
    } else {
        //after clicking Cancel
    }
});

对于您的代码示例,您可以尝试以下操作:

function performDelete ( a_element ) {
    // perform your delete here
    // a_element is the <a> tag that was clicked
}

function confirmAction ( a_element, message, action ) {
    alertify.confirm(message, function(e) {
        if (e) {
            // a_element is the <a> tag that was clicked
            if (action) {
                action(a_element);
            }
        }
    });
}

<a href="#" onclick="confirmAction(this, 'Are you sure you wish to remove this?', performDelete); return false;">Delete</a>

编辑:更新为通用确认对话框,如果用户单击“确定”,则调用回调函数。

5gfr0r5j

5gfr0r5j2#

我可以解决这个问题,我的解决方案asnyc await函数:
示例:

{

function confirmDialogAsync(message = "", okText="Yes", cancelText="No") {
        return new Promise((resolve) => {
            alertify.confirm(
                message, 
                () => {resolve(true);},
                () => {resolve(false);}
            )
            .set({ title: " " })
            .set({ labels: { ok: okText, cancel: cancelText } });
        });
      }

const saveControlValidation = async () => {

console.log(1); 

 if (!(await confirmDialogAsync("Hello Salih ŞEKER","Hi","Bye"))) {
               return false;
    }

console.log(2);

}

}

相关问题