使用javascript自定义确认对话框 [英] Custom confirm dialog with javascript

查看:192
本文介绍了使用javascript自定义确认对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个类似于 confirm()的javascript函数,它显示一个对话框(带有问题和2个按钮的div),并返回 false ,则返回true。



可以使用javascript / jQuery但插件(例如jQuery UI或Dialog)?因为我想减少大小和往返时间...



我试图写这个代码,但我不知道如何使函数wait



/ p>

我想以这种方式使用我的函数:

  = myConfirm(Are you sure?)

上下文,只需更改作为参数传递的问题。这与 confirm()相同。

解决方案

不等待用户的输入,然后从函数返回,在JavaScript中更常见的是提供一个回调函数,当您等待的操作完成时,它将被调用。例如:

  myCustomConfirm(Are you sure?,function(confirmed){
if(confirmed){
//如果他们点击确认你需要做什么确认
} else {
//如果他们点击就需要做的事情取消
}
});

这可以按照以下行来实现:

  function myCustomConfirm(message,callback){
var confirmButton,cancelButton;

//创建用户界面,显示消息等。

confirmButton.onclick = function(){callback(true); };
cancelButton.onclick = function(){callback(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 click "Ok" or false otherwise.

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" the user click.

Thanks in advice!

[EDIT]

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 parameter. This is the same behavior of confirm()

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆