Javascript事件处理和流程控制 [英] Javascript event handling and flow control

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

问题描述

我正在尝试根据提供的输入来构建一个加载的网页。基本上我在JavaScript中遇到事件处理时遇到麻烦。来自python,如果我想等待一个特定的键盘输入,然后再移动到下一个对象来显示,我将创建一个循环,并在其中放置一个关键的监听器。

I'm attempting to build a webpage that loads depending on the input provided. I'm having some trouble wrapping my head around event handling in javascript, basically. Coming from python, if I wanted to wait for a specific keyboard input before moving on to the next object to display, I would create a while loop and put a key listener inside it.

Python:

def getInput():
  while 1:
    for event in pygame.event.get(): #returns a list of events from the keyboard/mouse
      if event.type == KEYDOWN:
        if event.key == "enter": # for example
          do function()
          return
        elif event.key == "up":
          do function2()
          continue
        else: continue # for clarity

在DOM / javascript中尝试找到一种实现此方法的方法,我似乎只是崩溃的页面(我假设由于While循环),但我认为这是因为我的事件处理写得不好。另外,使用element.onkeydown = function;注册事件处理程序我很难把我的头包围,而setInterval(foo(),interval)没有给我带来很大的成功。

In trying to find a way to implement this in DOM/javascript, I seem to just crash the page (I assume due to the While Loop), but I presume this is because my event handling is poorly written. Also, registering event handlers with "element.onkeydown = function;" difficult for me to wrap my head around, and setInterval(foo(), interval] hasn't brought me much success.

基本上,我想要一个听循环对关键字X执行某种行为,但是当键Y被击中时会中断。

Basically, I want a "listening" loop to do a certain behavior for key X, but to break when key Y is hit.

推荐答案

在JavaScript中,您放弃控制主循环浏览器运行主循环并在事件或超时/间隔发生时回调到代码中,您必须处理该事件,然后返回,以便浏览器可以执行其他操作,触发事件,等等。

In JavaScript, you give up control of the main loop. The browser runs the main loop and calls back down into your code when an event or timeout/interval occurs. You have to handle the event and then return so that the browser can get on with doing other things, firing events, and so on.

所以你不能有一个听循环,浏览器为你做,给你事件,让你处理它,但一次您已经完成处理必须返回的事件,您不能回到不同的循环中,这意味着您无法编写分步过程代码;如果您有事件调用之间持续存在的状态,则必须存储它,例如在变量中。

So you cannot have a ‘listening’ loop. The browser does that for you, giving you the event and letting you deal with it, but once you've finished handling the event you must return. You can't fall back into a different loop. This means you can't write step-by-step procedural code; if you have state that persists between event calls you must store it, eg. in a variable.

此通知ach无法工作:

This approach cannot work:

<input type="text" readonly="readonly" value="" id="status" />

var s= document.getElementById('status');
s.value= 'Press A now';
while (true) {
    var e= eventLoop.nextKeyEvent(); // THERE IS NO SUCH THING AS THIS
    if (e.which=='a')
        break
}
s.value= 'Press Y or N';
while (true) {
    var e= eventLoop.nextKeyEvent();
    if (e.which=='y') ...

Step-by - 步骤代码必须被翻转,以便浏览器调用您,而不是调用浏览器:

Step-by-step code has to be turned inside out so that the browser calls down to you, instead of you calling up to the browser:

var state= 0;
function keypressed(event) {
    var key= String.fromCharCode(event? event.which : window.event.keyCode); // IE compatibility
    switch (state) {
        case 0:
            if (key=='a') {
                s.value= 'Press Y or N';
                state++;
            }
            break;
        case 1:
            if (key=='y') ...
            break;
    }
}

s.value= 'Press A now';
document.onkeypress= keypressed;

您还可以使代码看起来更线性化,并使用嵌套清理一些状态匿名功能:

You can also make code look a little more linear and clean up some of the state stuff by using nested anonymous functions:

s.value= 'Press A now';
document.onkeypress= function(event) {
    var key= String.fromCharCode(event? event.which : window.event.keyCode);
    if (key=='a') {
        s.value= 'Press Y or N';
        document.onkeypress= function(event) {
            var key= String.fromCharCode(event? event.which : window.event.keyCode);
            if (key=='y') ...
        };
    }
};

这篇关于Javascript事件处理和流程控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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