Why does mousedown event listener run through function?

允我心安 提交于 2019-12-02 18:48:11

问题


I drew a canvas, and then with the code

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

I added an event listener to run clicked whenever I click the mouse. But when I went through the code line by line on chrome, the moment it adds the event listener it automatically runs the function clicked anyway, but I only want it to run the function when I click.

Am I doing something wrong?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/21806064/why-does-mousedown-event-listener-run-through-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!