最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Calling addEventListener on a element produce a "Not enough arguments" error - Stack Overflow

programmeradmin1浏览0评论

My code works on Chrome but not on Firefox... in Firefox... whenever this piece of code launches..

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:

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...

My code works on Chrome but not on Firefox... in Firefox... whenever this piece of code launches..

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:

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...

Share Improve this question edited Jul 15, 2016 at 19:39 Braiam 4,49611 gold badges49 silver badges83 bronze badges asked Aug 10, 2012 at 18:58 testtest 18.2k67 gold badges172 silver badges245 bronze badges 2
  • 6 The second argument to addEventListener should be the callback function. See: developer.mozilla.org/en-US/docs/DOM/element.addEventListener – asawyer Commented Aug 10, 2012 at 19:00
  • 2 Of course that is javascript. The JQuery echivalent is .on – Samson Commented Aug 10, 2012 at 19:01
Add a comment  | 

3 Answers 3

Reset to default 11

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.

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.

You could also use JQuery to bind the keydown event to the canvas.

$('#canvas').on("keydown", function(event){
    // code
});
发布评论

评论列表(0)

  1. 暂无评论