简体   繁体   中英

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? 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.

 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.

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

This is what I end up with for aBtn1: <input type="button" name="aBtn1" value="Test" onclick="(() => console.log('test button clicked'))()" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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