简体   繁体   中英

Why should we use anonymous functions with jQuery instead of the function directly?

Some jQuery methods expect a function as a parameter, but to work they should receive an anonymous function as a parameter rather than a function directly, as in the following example:

$("a").on("click", function () { retornaNada(); }); 

rather than

 $("a").on("click", retornaNada());

Consider retornaNada() as a function without any body of code. Why can not we pass the function directly?

It's working but you need to pass only the function reference (name) like this :

function test (e) {
    console.log('test ok');
}
$('body').on('click', test);

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