使用JavaScript自定义确认对话框 [英] Custom confirm dialog with JavaScript
问题描述
我想创建一个类似于 confirm()
的JavaScript函数,它显示一个对话框(带有问题的div和2个按钮),并返回 true
如果用户点击Ok或 false
否则。
I would like to create a JavaScript function similar to confirm()
that shows a dialog (a div with a question and 2 buttons) and returns true
if the user clicks "Ok" or false
otherwise.
是吗可能使用JavaScript / jQuery但不使用插件(例如jQuery UI或Dialog)?因为我试图减小大小和往返时间...
Is it possible to do that using JavaScript/jQuery but without plugins (e.g. jQuery UI or Dialog)? Because I'm trying to reduce size and round trip times...
我试图写这个代码,但是我不知道如何使这个功能等待对于用户点击。
I tried to write this code, but I don't know how to make the function "wait" for the user click.
我想以这种方式使用我的功能:
I would like to use my function in this way:
answer=myConfirm("Are you sure?")
这样我可以在几个上下文中使用相同的函数,只需更改作为参数传递的问题。这是确认()相同的行为
In this way I could use the same function in several contexts, simply changing the question passed as a parameter. This is the same behavior of confirm()
推荐答案
而不是等待用户的输入,然后从函数返回,在JavaScript中更常见的是提供一个回调函数,当您执行等待完成。例如:
Rather than waiting for the user's input and then returning from the function, it is more common in JavaScript to provide a callback function that will be called when the action you're waiting for is complete. For example:
myCustomConfirm("Are you sure?", function (confirmed) {
if (confirmed) {
// Whatever you need to do if they clicked confirm
} else {
// Whatever you need to do if they clicked cancel
}
});
这可以按照以下方式实施:
This could be implemented along the lines of:
function myCustomConfirm(message, callback) {
var confirmButton, cancelButton;
// Create user interface, display message, etc.
confirmButton.onclick = function() { callback(true); };
cancelButton.onclick = function() { callback(false); };
}
这篇关于使用JavaScript自定义确认对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!