How can I reproduce the “wait” functionality provided by JavaScript's confirm() function?

这一生的挚爱 提交于 2020-01-15 07:50:09

问题


I'm trying to write a custom in-window confirm dialog (based on jQuery UI) that we can use to control all aspects of the window (button text, etc). What I'd really like is for the control to behave exactly the way that the built-in confirm() function behaves (call confirm(), script execution pauses until the user clicks ok or cancel, confirm() returns true or false). I have looked around to find solutions for this, and the closes that I have come looks something like this:

//title = text to be displayed for title
//text = text to be displayed in body of dialog
//func = name of function to be called upon user selection, result will be passed as first parameter
function aw_confirm(title, text, func){
    <%= ClientID %>_retVal = null;
    <%= ClientID %>_func = func;
    <%= ClientID %>_show(title, text);
    <%= ClientID %>_waitForSelection(func);
}

function <%= ClientID %>_waitForSelection(func){
    if (<%= ClientID %>_retVal != null){
        var r = <%= ClientID %>_retVal;
        <%= ClientID %>_retVal = null;
        func(r);
    }
    else setTimeout("<%= ClientID %>_waitForSelection(<%= ClientID %>_func)", 10);
}

This is an aspx control, thus the <%= ClientID %>_ before everything in order to make sure that nobody overwrites the functions with code in other controls.

As you can see, this current setup requires the programmer to write a handler (here called func) to be called when the user makes a selection. What I'd really like is for aw_confirm() to just wait until the user makes a selection and then return. Is there a way to do this? Thanks in advance for any help or advice you can provide!


回答1:


Javascript is mostly event-based. The code reacts to events (a clicked button, a timer etc). JQuery UI also follows this paradigm. What you are trying is working against this and will be therefore quite hard if even possible. You should follow the event based approach.

It doesn't have to be much different from the code which uses confirm. If you had this:

ret = confirm("Hello User")
// do something

you could now write

aw_confirm("Hello user", "", function(ret){
  // do something
})

using an anonymous function as callback.



来源:https://stackoverflow.com/questions/3822118/how-can-i-reproduce-the-wait-functionality-provided-by-javascripts-confirm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!