简体   繁体   中英

Assigning functions to events in javascript

I have a question about the onchange event for a dropdown list. I've been doing some reading and found that the preferred way to handle the change event is:

select.onchange = function(){animateMarker()};

I was just wondering why it couldn't just be:

select.onchange = animateMarker();

What is the function() preceding animateMarker() doing?

Thanks.

You can do this:

select.onchange = animateMarker;

Adding the () executes the function immediately, removing them means that you're assigning the function to the event handler, so that it will be executed eventually.

And to answer the last part: the function () {} that wraps animateMarker is unnecessary, it is simply an anonymous function that executes the animateMarker function when it is called.

As @mrwillihog said you can assign it directly with it's definition like select.onchange = animateMarker; however it's wise to use a wrapper function as advised since by doing so you may add more functions later to the onchange event by inserting into the wrapper function. Otherwise you will be limited with only animateMarker event... or... you might need to redefine the animateMarker and do some ugly monkey patches. So it's best to use a wrapper function.

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