简体   繁体   English

如何将内联 onclick 函数编写为 es6 箭头函数?

[英]How to write inline onclick function as es6 arrow function?

If this is duplicate let me know, but I see similar questions for react environment but not for pure html+js.如果这是重复的让我知道,但我看到类似的问题反应环境但不是纯 html+js。

The question is, I write js function as html onclick property and it is working :问题是,我将 js 函数编写为 html onclick 属性并且它正在工作:

<button onclick="function myFunction(){ alert('hi')} myFunction();">Hi</button>

But I can't write arrow function as html onclick prop like that :但是我不能像这样将箭头函数写为 html onclick prop:

<button onclick="()=>alert('hi')">Hi</button>

It is possible or not?可能还是不可能?

In the first example you assign a function to myFunction and then explicitly call myFunction .在第一个示例中,您将一个函数分配给myFunction ,然后显式调用myFunction

In the second example you create a function, but you don't assign it anywhere, and you don't call it.在第二个示例中,您创建了一个函数,但没有在任何地方分配它,也没有调用它。

You could可以……

onclick=" const myFunction = ()=>alert('hi'); myFunction() "

… but it is as completely pointless (and hard to read) as the first example. ……但它和第一个例子一样完全没有意义(并且难以阅读)。


There is no reason, in the scope of an onclick function or any other function to create a function and then call it once, immediately.没有理由在onclick函数或任何其他函数的范围内创建一个函数,然后立即调用它一次。


Just make the body of the onclick function do that directly:只需让onclick函数的主体直接执行此操作即可:

onclick="alert('hi')"

Better yet, assign your event handlers using JavaScript:更好的是,使用 JavaScript 分配您的事件处理程序:

document.querySelector("button")
    .addEventListener("click", () => alert("hi"));

You have to wrap it in parentheses and call it like an anonymous function in this way:你必须把它用括号括起来,并像匿名函数一样以这种方式调用它:

<button onclick="(() => alert ('hi'))()">Hi</button>

This is exactly how you would call an anonymous conventional function inline:这正是内联调用匿名常规函数的方式:

<button onclick="(function() { alert ('hi') })()">Hi</button>

The reason for this is, currently you've just declared a function, and every time you click, the function is declared but never called.这样做的原因是,当前您刚刚声明了一个函数,每次单击时,该函数都已声明但从未调用过。 With the adjustment in my answer, you define it and execute it each time a button is clicked.通过我的答案中的调整,您可以定义它并在每次单击按钮时执行它。

Yes, it is possible.对的,这是可能的。 Just adjust parantheses, and you dont't need to define another function actually :只需调整括号,实际上您不需要定义另一个函数:

<button onclick="(()=>alert('hi'))();">Hi</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM