gpt4 book ai didi

对象中的 Javascript 键盘事件

转载 作者:行者123 更新时间:2023-12-04 01:47:55 26 4
gpt4 key购买 nike

我的键盘以一种简单的方式工作:

rightPressed = false;

onKeyDown = function(pressEvent) {
if (pressEvent.keyCode == 39) rightPressed = true;
}
onKeyUp = function(pressEvent) {
if (pressEvent.keyCode == 39) rightPressed = false;
}

$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);

它奏效了。然后我试图把它全部放在一个类中:
function Tkeyboard(){
this.rightPressed = false;

this.onKeyDown = function(pressEvent) {
if (pressEvent.keyCode == 39) { this.rightPressed = true; alert("boom!"); }
}
this.onKeyUp = function(pressEvent) {
if (pressEvent.keyCode == 39) { this.rightPressed = false; }
}

$(document).keydown(this.onKeyDown);
$(document).keyup(this.onKeyUp);
}

在初始化中,我创建了一个对象:
keys = new Tkeyboard;

在主循环中,我采取了行动:
if ( keys.rightPressed ) { rx+=1;}

而现在它失败了。问题的有趣部分是 alert("boom!") 被调用,所以变量也应该被修改......

我会很感激任何想法。

最佳答案

keydown/up 回调在实际运行时会失去其原始范围。您需要 bind回调到 this .在 Prototype Framework ,你会这样做:

function Tkeyboard() {
this.rightPressed = false;

$(document).keydown(this.onKeyDown.bind(this));
$(document).keyup(this.onKeyUp.bind(this));
}

Tkeyboard.prototype.onKeyDown = function(pressEvent) {
if (pressEvent.keyCode == 39) { this.rightPressed = true; alert("boom!"); }
};
Tkeyboard.prototype.onKeyUp = function(pressEvent) {
if (pressEvent.keyCode == 39) { this.rightPressed = false; }
};

jQuery 中应该类似.

如果您需要了解如何构建完整的键盘类,请查看 the one I wrote .

关于对象中的 Javascript 键盘事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5206723/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com