我在询问之前已经寻找了现有的答案,但是找不到我想要的东西,或者它已经超出我的头了。
我正在学习JS,想扩展我的课程尚未完全涵盖的内容。基本上,使用vanilla JavaScript,我想将按键与[“ w”,“ a”,“ s”,“ d”]进行比较。
这是我的代码:
function moveCommand(direction) {
var whatHappens;
switch (direction) {
case direction === event.key["w"]:
var outcome = battle(1) ? "run your sword through it! Gain 25 exp!" : "take serious damage. Gain 5exp. Lose 20hp.";
whatHappens = "You encounter a monster and " + outcome;
break;
case direction === event.key["a"]:
whatHappens = "You arrived home";
break;
case direction === event.key["s"]:
// player.gold += 15;
whatHappens = "You found 15 gold!";
break;
case direction === event.key["d"]:
var outcome = battle(2) ? "send it packing! Gain 10exp!" : "get pelted with stones. Gain 2exp. Lose 10hp.";
whatHappens = "You run into a troll and " + outcome;
break;
default:
whatHappens = "Please enter a valid direction";
}
return whatHappens;
}
document.addEventListener('keypress', moveCommand);
我理解为什么这不起作用(按键可能没有传递给'direction',并且我检查event.key的语法可能不正确),但是我找不到如何使它起作用。如果没有jQuery或其他扩展名,它甚至可能吗?
switch语句以及如何处理事件存在问题,请通读文档以了解如何使用switch statements,请注意,对于按下事件,switch语句在case
内不需要条件, event.key已经返回了按键的字母,这是我制作的一个片段,以展示如何使其工作,由于您不包括它,因此我删除了battle()
,这是一个有效的片段:
function moveCommand(event) {
var whatHappens;
switch (event.key) {
case 'w':
var outcome = 1 ? "run your sword through it! Gain 25 exp!" : "take serious damage. Gain 5exp. Lose 20hp.";
whatHappens = "You encounter a monster and " + outcome;
break;
case 'a':
whatHappens = "You arrived home";
break;
case 's':
// player.gold += 15;
whatHappens = "You found 15 gold!";
break;
case 'd':
var outcome = 1 ? "send it packing! Gain 10exp!" : "get pelted with stones. Gain 2exp. Lose 10hp.";
whatHappens = "You run into a troll and " + outcome;
break;
default:
whatHappens = "Please enter a valid direction";
}
console.log(whatHappens)
}
document.addEventListener('keypress', moveCommand);