[英]JavaScript if statement suddenly stopped working
I am making a pong project right now, and I have a bit of code that lets changing directions be more smooth, so when you press both keys at the same time it won't freeze up for a moment.我现在正在做一个乒乓球项目,我有一些代码可以让改变方向更加顺畅,所以当你同时按下两个键时,它不会暂时冻结。 This happens in the up() function below.
这发生在下面的up() function 中。
let rx = 0;
pressDown =
document.addEventListener('keydown', down);
pressUp =
document.addEventListener('keyup', up);
function down(){
if(event.keyCode === 39){
rx = 3;
}
if(event.keyCode === 37){
rx = -3;
}
}
function up(){
if (rx < 0 && event.keyCode === 37){
rx = 0;
}
if (rx > 0 && event.keyCode === 39){
rx = 0;
}
}
It was working fine the other day, but when I opened my project this morning, this if statement suddenly did not work.前几天它工作得很好,但是当我今天早上打开我的项目时,这个 if 语句突然不起作用。 The first part of the code does not work either until I change the second one by removing the
rx < 0
and rx > 0
.代码的第一部分也不起作用,直到我通过删除
rx < 0
和rx > 0
来更改第二部分。 I tried switching the <
and >
as well, but it did nothing.我也尝试切换
<
和>
,但它什么也没做。 Does anyone have an answer or a solution?有人有答案或解决方案吗?
Looks like there are a few problems with your implementation:看起来您的实现存在一些问题:
You want the down
and up
function both to accept an event
parameter (called e
in my example).您希望
down
up
都接受event
参数(在我的示例中称为e
)。
Your down
function had a missing closing brace.您的
down
function 缺少右括号。 Not sure if that was a copy/paste error or if that was present in your original code.不确定这是否是复制/粘贴错误,或者是否存在于您的原始代码中。
The rx
variable was never declared - maybe also a copy/paste error. rx
变量从未被声明——也可能是一个复制/粘贴错误。
Take a look at the snippet I included below - it might be a helpful reference.看看我在下面包含的片段 - 它可能是一个有用的参考。
Good luck!祝你好运!
let rx = 0; const rxValueEl = $("#rx-value"); function down(e) { if (e.keyCode === 39) { rx = 3; } if (e.keyCode === 37) { rx = -3; } // Sets value on page rxValueEl.html(rx); } function up(e) { if (rx < 0 && e.keyCode === 37) { rx = 0; } if (rx > 0 && e.keyCode === 39) { rx = 0; } // Sets value on page rxValueEl.html(rx); } document.addEventListener('keydown', down); document.addEventListener('keyup', up);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p>RX value:</p> <p id="rx-value">0</p> <p>Hit left + right arrows to change rx value</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.