javascript 自定义javascript确认对话框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19977745/
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
Custom javascript confirm dialog box
提问by Shahe Masoyan
I have a function called showModalConfirmDialog
that creates a custom javascript made dialog box with two buttons Yes/No and dims the background. Now in my functions I want to call that function like:
我有一个函数showModalConfirmDialog
,它创建一个自定义的 javascript 制作的对话框,其中有两个按钮是/否,并使背景变暗。现在在我的函数中,我想调用该函数,如:
var outcome = showModalConfirmDialog('Are you sure?');
and I want to react depending on the button clicked;
我想根据点击的按钮做出反应;
if(outcome == true){
// do something
} else {
// do something else
}
The buttons return true/false. Javascript code:
按钮返回真/假。Javascript代码:
button1.onclick = function(evt){
return true;
};
button2.onclick = function(evt){
return false;
};
I don't know what I am missing, any help would be appreciated. Thanks
我不知道我错过了什么,任何帮助将不胜感激。谢谢
回答by leaf
You can't reproduce the behaviour of the native modal. Instead you could use callbacks.
您无法重现本机模态的行为。相反,您可以使用回调。
This way :
这条路 :
function showModalConfirmDialog(msg, handler) {
button1.onclick = function(evt){
handler(true);
};
button2.onclick = function(evt){
handler(false);
};
}
showModalConfirmDialog('Are you sure?', function (outcome) {
alert(outcome ? 'yes' : 'no');
});
Or this way :
或者这样:
function showModalConfirmDialog(msg, confirmHandler, denyHandler) {
button1.onclick = confirmHandler;
button2.onclick = denyHandler;
}
showModalConfirmDialog(
'Are you sure?',
function () { alert('yes'); },
function () { alert('no'); }
);