Javascript - 根据keypressed获取单词

时间:2014-02-05 20:56:46

标签: javascript keypress

在这里搜索,我找到了this tutorial,这真的很有帮助。我可以轻松地按document.onkeypress来按下键,并String.fromCharCode()将键码转换为可读的字符。但我想知道如何能够检测到特定的单词?

像:

var words; // something to store the latest 3 words for example

// then somehow concatenate each key pressed
// separating in the array based on the space key

var all = words[0]+" "+words[1]+" "+words[2];
var lastTwo = words[1]+" "+words[2];
if(all == "i love you"){
   alert("I love you too :)"); 
}else if(lastTwo = "screw you"){
   alert("You should not say something like this to me");
}

编辑:我真正感兴趣的是如何以递归方式连接密钥?

2 个答案:

答案 0 :(得分:2)

首先,您需要将数组元素构建为字符串:

var phrase = words.join(" ");

然后看看那里有什么。

if(phrase.indexOf('sandwiches')>-1) {
     alert("found sandwiches! let's eat.");
}

答案 1 :(得分:1)

我唯一的问题是我正在使用nano直接在服务器上编辑html文件,所以我只是犯了一些我无法识别的错误。

基本上做:

var word = "";
function dump(e){
  var unicode = e.keyCode? e.keyCode : e.charCode;
  var actualkey = String.fromCharCode(unicode);
  word += actualkey;
  alert(word);
}
document.onkeypress = dump

我能够看到连接的键是我的主要问题。之后我会将值调整为数组,并像@Diodeus建议的那样整齐地加入它们。