简体   繁体   English

我的 Javascript 代码未检测到输入

[英]My Javascript Code isn't detecting input

I have been trying to get input to work on my javascript code and it won't detect input no matter what!我一直在尝试获取输入以处理我的 javascript 代码,无论如何它都不会检测到输入! I've been checking everywhere and it doesn't work!我到处检查,它不起作用!

 <!Doctype HTML> <html> <head> <title>Input Test</title> </head> <body> <!--<button onClick="main()">Start Game</button>--> <p id = "test"> </p> </body> <script> main(); function main() { create(); } function create() { var keystate; keystate = {}; // keep track of keyboard presses document.addEventListener("keydown", function(evt) { keystate[evt.keyCode] = true; }); document.addEventListener("keyup", function(evt) { delete keystate[evt.keyCode]; }); var Up_Key = 38; setInterval("update()", 100); } function update() { //document.getElementById("test").innerHTML = "twerks"; if (keystate[Up_Key]) { document.getElementById("test").innerHTML = "works"; } } </script> </html>

I've been using some tutorials and I just want input detection.我一直在使用一些教程,我只想要输入检测。

The variables keystate and Up_Key are defined inside the create function, but you're trying to use them inside another function named update .变量keystateUp_Keycreate函数中定义,但您试图在另一个名为update函数中使用它们。 They'll be undefined there, since it's in another scope.它们将在那里undefined ,因为它在另一个范围内。

If you declare those variables outside the functions, your code will work fine.如果您在函数之外声明这些变量,您的代码将正常工作。

It's better to encapsulate all your code in an IIFE (Immediately invoked function expression), so you don't polute the global scope, with global variables.最好将所有代码封装在 IIFE(立即调用的函数表达式)中,这样您就不会用全局变量污染全局范围。 As Google says:正如谷歌所说:

An immediately-invoked function expression (or IIFE, pronounced "iffy") is a JavaScript design pattern which produces a lexical scope using JavaScript's function scoping.立即调用的函数表达式(或 IIFE,发音为“iffy”)是一种 JavaScript 设计模式,它使用 JavaScript 的函数作用域生成词法作用域。

Here is your code updated and working:这是您的代码更新和工作:

 <!DOCTYPE HTML> <html> <head> <title>Input Test</title> </head> <body> <p id="test"></p> </body> <script> (function() { var keystate = {}; var Up_Key = 38; main(); function main() { create(); } function create() { // keep track of keyboard presses document.addEventListener("keydown", function(evt) { keystate[evt.keyCode] = true; }); document.addEventListener("keyup", function(evt) { delete keystate[evt.keyCode]; }); setInterval(update, 100); } function update() { if (keystate[Up_Key]) { document.getElementById("test").innerHTML = "works"; } } })(); </script> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM