[英]Javascript function not registering keypress
I'm trying to get a function to stop when the enter key is pressed but for some reason it is not registering my enter
variable's switch from false to true. 我试图使按下Enter键时停止的功能停止 ,但是由于某种原因,它没有注册我的
enter
变量从false到true的切换。 I don't know if this is a scope issue or a closure issue or a binding issue, I've looked throughout the forums and tried a bunch of different solutions but nothing seems to work... 我不知道这是范围问题,关闭问题还是约束性问题,我在各个论坛中四处寻找并尝试了许多不同的解决方案,但似乎没有任何效果……
function positionArrow(arrow) {
var enter = false;
$(document).keypress(function(e) {
if(e.which == 13) {
enter = true;
}
});
console.log(enter);
if (enter == true) {
return;
} else {
$(arrow.element).css({
left: arrow.x - arrowWidth / 2,
top: arrow.y - arrowHeight / 2
});
rotate(arrow.element, arrow.angle);
}
}
You should have the code you want to run within your handler, and also your handler should be outside of your "positionArrow" function. 您应该具有要在处理程序中运行的代码,并且处理程序也应位于“ positionArrow”函数之外。 Try replacing
enter = true;
尝试替换
enter = true;
with 同
$(arrow.element).css({
left: arrow.x - arrowWidth / 2,
top: arrow.y - arrowHeight / 2
});
rotate(arrow.element, arrow.angle);
And moving your handler declaration outside of the function. 并将处理程序声明移到函数之外。 Code should look like this
代码应如下所示
$(document).keypress(function(e) {
if(e.which == 13) {
positionArrow(arrow);
}
}
function positionArrow(arrow) {
$(arrow.element).css({
left: arrow.x - arrowWidth / 2,
top: arrow.y - arrowHeight / 2
});
rotate(arrow.element, arrow.angle);
}
I managed to get it to work with the method below. 我设法使其与下面的方法一起使用。 I made
enter
a global variable and created a separate function. 我
enter
了一个全局变量并创建了一个单独的函数。 While this works, I feel there may be a better solution out there or a better articulation of what the problem was to begin with. 在此方法奏效的同时,我觉得可能有更好的解决方案或对问题的根源有更好的阐述。
var enter = false;
function stopArrow(){
$(document).keypress(function(e) {
if(e.which == 13) {
enter = true;
}
});
}
stopArrow();
function positionArrow(arrow) {
if (enter == true) {
return;
} else {
$(arrow.element).css({
left: arrow.x - arrowWidth / 2,
top: arrow.y - arrowHeight / 2
});
rotate(arrow.element, arrow.angle);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.