使用 JavaScript 自定义确认对话框 [英] Custom confirm dialog with JavaScript
问题描述
我想创建一个类似于 confirm()
的 JavaScript 函数,它显示一个对话框(一个带有问题和 2 个按钮的 div)并返回 true
如果用户否则点击确定"或 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?")
通过这种方式,我可以在多个上下文中使用相同的函数,只需更改作为参数传递的问题即可.这与 confirm()
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屋!