Javascript Alertify 从确认返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14408627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Alertify with return from confirm
提问by jfreak53
I'm trying to use alertify.js
as a confirmation dialog for all my confirm scripts. But it just isn't working like regular JS confirm
does. In the code below I never get a return true
我正在尝试将其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>
Of course if I replace aConf
with JS' confirm
it works. So why is alertify
not sending me back it's outcome?
当然,如果我aConf
用 JS替换confirm
它就可以了。那么为什么alertify
不把它的结果发回给我呢?
回答by Levi
Because confirm is a blocking function (no javascript will run until it returns true/false), and alertify is non-blocking (JS keeps executing). Alertify does not immediately return a true/false, but instead, it probably returns undefined immediately, then it calls a callback function later, after the user clicks OK or Cancel. The return value from that callback function has no effect in your example, because the onclick code has already finished running (because it is non-blocking).
因为confirm 是一个阻塞函数(在返回true/false 之前不会运行javascript),而alertify 是非阻塞函数(JS 不断执行)。Alertify 不会立即返回真/假,而是可能会立即返回 undefined,然后在用户单击“确定”或“取消”后稍后调用回调函数。该回调函数的返回值在您的示例中无效,因为 onclick 代码已经完成运行(因为它是非阻塞的)。
Assuming you are using this: https://github.com/fabien-d/alertify.js/
假设你正在使用这个:https: //github.com/fabien-d/alertify.js/
This is how it actually works with a callback function, not a return value:
这是它与回调函数的实际工作方式,而不是返回值:
alertify.confirm( message, function (e) {
if (e) {
//after clicking OK
} else {
//after clicking Cancel
}
});
For your code sample, you might try something like this:
对于您的代码示例,您可以尝试以下操作:
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>
EDIT: updated to be a generic confirm dialog that calls a callback function if the user clicks ok.
编辑:更新为通用确认对话框,如果用户单击确定,则调用回调函数。