10

我正在尝试将alertify.js其用作所有确认脚本的确认对话框。但它不像普通的 JSconfirm那样工作。在下面的代码中,我从来没有得到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>

当然,如果我aConf用 JS'替换confirm它就可以了。那么为什么alertify不把结果寄回给我呢?

4

1 回答 1

11

因为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>

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

于 2013-01-18T22:28:58.310 回答