为什么我们应该使用jQuery而不是函数直接使用匿名函数?
问题描述:
有些jQuery方法期望函数作为参数,但是为了工作,它们应该直接接收匿名函数作为参数而不是函数,如下例所示:
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(); });
而不是
$("a").on("click", retornaNada());
考虑 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);