[英]Arrow Function not working for an onClick event handler
Is it possible to use arrow function as I have on the first button's (aBtn1) onclick event handler?是否可以像我在第一个按钮(aBtn1)的 onclick 事件处理程序上那样使用箭头函数? Can someone please explain why the first approach fails?有人可以解释为什么第一种方法失败吗?
<script>
var arrFunc = () => {
console.log('test btn clicked');
};
</script>
<form>
<label for="name">Name</label>
<input type="text" value="" id="name" />
<input type="button" name="aBtn1" value="Test" onclick="() => { console.log('test button clicked'); }" />
<input type="button" name="aBtn2" value="Test" onclick="arrFunc();" />
<input type="submit" value="Submit" />
</form>
The first option only declares a function w/o calling it.第一个选项只声明一个没有调用它的函数。 You need to call it after the declaration.您需要在声明之后调用它。 (() => { console.log('test button clicked'); })()
which makes little sense you could simply use the body of the function. (() => { console.log('test button clicked'); })()
这没什么意义,你可以简单地使用函数体。
var arrFunc = () => { console.log('test btn clicked'); };
<form> <label for="name">Name</label> <input type="text" value="" id="name" /> <input type="button" name="aBtn1" value="Test" onclick="(() => { console.log('test button clicked'); })()" /> <input type="button" name="aBtn2" value="Test" onclick="arrFunc();" /> <input type="submit" value="Submit" /> </form>
The value of an onclick
attribute is the body of a function. onclick
属性的值是函数的主体。
You have created a function which defines an arrow function.您已经创建了一个定义箭头函数的函数。
You never call that function.你永远不会调用那个函数。 You never assign that function to a variable.您永远不会将该函数分配给变量。 You never do anything with that function.你永远不会用那个函数做任何事情。
This worked for me: I removed the curly braces and the semicolon from aBtn1这对我有用:我从 aBtn1 中删除了花括号和分号
This is what I end up with for aBtn1: <input type="button" name="aBtn1" value="Test" onclick="(() => console.log('test button clicked'))()" />
这就是我对 aBtn1 的最终结果: <input type="button" name="aBtn1" value="Test" onclick="(() => console.log('test button clicked'))()" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.