javascript - 如何使用箭头功能来提醒某些事情

标签 javascript arrow-functions

我有这张带有该功能的图像 onclick

<img src="assets/images/logo.svg" id="logo" onclick="alertPlay()">

如果我创建以下函数,它不应该起作用吗?

const alertPlay => alert("play");

如果没有,也许我只是对一般的箭头函数感到困惑。

还有,有没有简写,比如

<img src="assets/images/logo.svg" id="logo" onclick="alert('play')">

最佳答案

您使用了错误的语法。 () =>alert("play"); 是函数体。您需要使用 = 将其分配给变量。
OP 在评论中问道:另外,为什么我要把 () 放在 ==> 之间:
因为它的正确语法由 docs 描述。

The parameter list for a function with no parameters should be written with a pair of parentheses.

const alertPlay = () => alert("play");
<img src="assets/images/logo.svg" id="logo" onclick="alertPlay()">

关于javascript - 如何使用箭头功能来提醒某些事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55007193/

相关文章:

javascript - 如何从 select 元素中获取所选选项的文本?

javascript - 本地图设置了 'restriction' 选项时,map.fitBounds 的工作很奇怪

javascript - react native : Redirecting axios to a different address upon error

javascript - HTML5 Canvas 创建的 JPEG 是 "corrupt"还是 "damaged"?

coffeescript - CoffeeScript:如何同时使用粗箭头和该箭头?

javascript - 箭头函数中的 "this"与该箭头函数之外的 "that"中的 "var that = this"是否相同?

javascript - 无缓存和 cookie 问题

javascript - 为什么我不能在 JavaScript/ES6 中使用带有箭头函数的 `new`?

javascript - 如何将此 if 语句转换为箭头函数?

javascript - ES6 箭头函数和使用 Function.prototype.bind 绑定(bind)的函数之间有什么区别(如果有的话)?