Why does mousedown event listener run through function?

前端 未结 2 579
误落风尘
误落风尘 2021-01-26 02:28

I drew a canvas, and then with the code

canvas.addEventListener(\"mousedown\", clicked(event), false);

I added an event listener to run clicked

相关标签:
2条回答
  • 2021-01-26 02:49

    canvas.addEventListener("mousedown", clicked,false);

    0 讨论(0)
  • 2021-01-26 02:54

    You need to just pass the function reference and not actually call it like this:

    canvas.addEventListener("mousedown", clicked, false);
    

    Then, the function should be defined like this:

    function clicked(event) {
        // code here
    }
    

    When you include parens after the function name, it is immediately executed and it's return value is what is passed to addEventListener() which is probably not what you wanted at all. Leave off the parens to just pass a function reference.

    0 讨论(0)
提交回复
热议问题