为什么mousedown事件监听器运行通过函数? [英] Why does mousedown event listener run through function?

查看:171
本文介绍了为什么mousedown事件监听器运行通过函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我画了一个画布,然后用代码

I drew a canvas, and then with the code

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

我添加了一个事件监听器,
但是当我在chrome上逐行浏览代码时,添加事件监听器的那一刻,它会自动运行单击的函数,但我只希望它在我单击时运行该函数。

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.

我做错了什么?

推荐答案

你需要传递函数引用实际上不像这样调用:

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
}

当在函数名后包含括号时,立即执行,它的返回值是传递给 addEventListener()可能不是你想要的。省略括号以传递函数引用。

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.

这篇关于为什么mousedown事件监听器运行通过函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆