等待用户事件 [英] Wait for a user event

查看:158
本文介绍了等待用户事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个JavaScript类(使用jQuery)来创建自定义弹出窗口,但我无法弄清楚如何暂停脚本等待用户响应(单击确定按钮或取消)

I'm developing a javascript class (with jQuery) to create custom popup, but I can not figure out how to "pause" the script to wait for user response (click on the OK button or cancel)

类是这样的:

function Popup()
{
}

Popup.Show = function(text)
{
    var _response;
    /* code to draw the popup elements*/

    $("#button-ok").on("click",function()
    {
        _response = "ok!"
    }

    return _response
}

如果例如在警报中使用它,方法总是返回undefined,因为它不等待用户点击

if, for example, use it in an alert, the method always return "undefined", because it does not wait for user click

alert(Popup.Show("hello"))
//return undefined before the popup appears

我尝试使用这样的while循环:

I tried to use a while loop like this:

Popup.Show = function(text)
{
    var _response;
    var _wait = true;

    /* code to draw the window */

    $("#button-ok").on("click",function()
    {
        _wait = false;
        _response = "ok!"
    }

    while(_wait){};

    return _response
}

但不工作(正如我预期的)

but does not work (as I expected)

然后,我如何等待用户cli ck?

Then, how do I wait for the user click?

感谢所有

推荐答案

试图做,为什么是一个小小的,因为你似乎试图重建警报功能。但是'alert'是一个由浏览器设置的窗口函数。这个问题似乎与停止页面执行(如alert())功能重复。 a>

The context of what you are trying to do and why is a little vauge since it seems like you are trying to rebuild the 'alert' function. But 'alert' is a window function that is set up by the browser. This question seems like a duplicate of Stop page execution like the alert() function

其中基本上谈到回调链接,基本上封装了功能,以便您可以执行它们运行的​​顺序。我也认为你对代码的运行有一个根本的误解。正如所讨论的事件处理程序是异步的,而代码是按顺序读取的,在事件hanlders回调之前不会运行函数集,直到该事件被触发。

Which basically talks about callback chaining, essentially encapsulating functionality so you can enforce the order in which they run. I also think you have a fundamental misunderstanding of how the code is run. As discussed event handlers are asynchronous and while the code is read in order, it is not going to run the function set within the event hanlders callback until that event has been triggered.

这篇关于等待用户事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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