javascript 在元素上调用 addEventListener 会产生“参数不足”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11907653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling addEventListener on a element produce a "Not enough arguments" error
提问by test
My code works on Chrome but not on Firefox... in Firefox... whenever this piece of code launches..
我的代码在 Chrome 上工作,但在 Firefox 上不起作用......在 Firefox 中......每当这段代码启动时......
canvas.addEventListener('keydown');
I get this error:
我收到此错误:
Not enough arguments
[Break On This Error]
canvas.addEventListener('keydown');
I have var canvas
near the top as well as this:
我有var canvas
接近顶部以及这个:
canvas = document.getElementById("canvas");
canvas.width = 512;
canvas.height = 352;
context = canvas.getContext("2d");
I do not know why it works fine on Chrome but not Firefox...
我不知道为什么它在 Chrome 上运行良好,但在 Firefox 上运行不正常...
回答by Stephen Thomas
The addEventListener function needs a second parameter to specify the function that is called on the event. The real question is why Chrome doesn't generate an error.
addEventListener 函数需要第二个参数来指定对事件调用的函数。真正的问题是为什么 Chrome 不会产生错误。
回答by jfriend00
You need a function that executes when the event fires. It can be specified either inline like this:
您需要一个在事件触发时执行的函数。它可以像这样内联指定:
canvas.addEventListener('keydown', function(e) {
// your code here to handle the event
});
or it can be specified like this:
或者可以像这样指定:
function keyHandler(e) {
// your code here to handle the event
}
canvas.addEventListener('keydown', keyHandler);
Without an event handler function, there is nothing for the event handler to do as no code would execute when the event fires.
如果没有事件处理函数,事件处理函数就无事可做,因为在事件触发时不会执行任何代码。
回答by Anon
You could also use JQuery to bind the keydown event to the canvas.
您还可以使用 JQuery 将 keydown 事件绑定到画布。
$('#canvas').on("keydown", function(event){
// code
});