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. 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. Try replacing 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. 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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.