简体   繁体   English

onkeydown在Greasemonkey中不起作用

[英]onkeydown Not Working in Greasemonkey

I have written the following Greasemonkey script to add or remove cookies in the popular game Cookie Clicker. 我编写了以下Greasemonkey脚本来添加或删除流行游戏Cookie Clicker中的cookie。

function addCookies()
{
var cookiesString = prompt("How many cookies would you like to gain?");
var cookiesInt = Math.floor(cookiesString);
Game.Earn(cookiesInt);
alert("Your cookies have been added!");
}
function removeCookies()
{
var cookiesString2 = prompt("How many cookies would you like to remove?");
var cookiesInt2 = Math.floor(cookiesString2);
Game.cookies -= cookiesInt2;
alert("Your cookies have been removed.");
}
window.onkeydown = function(event) {
   if (event.keyCode === 81) {
      addCookies();
   }
   if (event.keyCode === 87) {
      removeCookies();
   }
   if (event.keyCode === 18) {
       alert('To add cookies, press "Q".  To remove cookies, press "W".');
};

For some reason, they code doesn't run when I press the "Q" key (or any other key, for that matter). 由于某些原因,当我按下“ Q”键(或其他任何键)时,它们的代码无法运行。 Does anyone have any idea why this may be? 有谁知道为什么会这样吗?

I ran it through JSLint, but all I got was just about the fact that the "Game" function wasn't defined. 我通过JSLint运行它,但是我所得到的只是关于未定义“游戏”功能的事实。 This is not the problem, because the code will be running on the webpage, which has defined the "Game" function. 这不是问题,因为代码将在定义了“游戏”功能的网页上运行。 Just to make sure, I removed those lines of code, and I still couldn't get the prompt to pop up with any key. 只是为了确保,我删除了这些代码行,但仍然无法获得提示以任何键弹出的提示。

Any help would be greatly appreciated. 任何帮助将不胜感激。

You're missing an end bracket on your final if statement. 您在最终的if语句中缺少结尾括号。 Corrected: 更正:

/* ...snip */
window.onkeydown = function(event) {
   if (event.keyCode === 81) {
      addCookies();
   }
   if (event.keyCode === 87) {
      removeCookies();
   }
   if (event.keyCode === 18) {
       alert('To add cookies, press "Q".  To remove cookies, press "W".');
   }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM