我正在尝试使用规则对象添加事件侦听器,如下所示
keyMap = [
{name: "Up", type: "keydown", code: 87, action: function(){alert("up")}},
{name: "Down", type: "keydown", code: 83, action: function(){alert("down")}},
{name: "Left", type: "keydown", code: 65, action: function(){alert("left")}},
{name: "Right", type: "keydown", code: 68, action: function(){alert("right")}}
]
for(var keyAct of keyMap){
if( typeof keyAct.action === "function" ){
document.addEventListener(keyAct.type, function(e){
if(e.keyCode === keyAct.code){
keyAct.action(e);
}
});
}
}
然后 w/a/s/d 按所有警报“正确”。我重写了for
这样的部分:
for(var keyAct of keyMap){
(function(keyAct){
if( typeof keyAct.action === "function" ){
document.addEventListener(keyAct.type, function(e){
if(e.keyCode === keyAct.code){
keyAct.action(e);
}
});
}
})(keyAct);
}
它有效,但这是唯一的方法吗?我可以做得更优雅吗?我的意思是,这看起来很奇怪。