Javascript 为什么';t$(functionName())工作吗?
此代码按预期工作:Javascript 为什么';t$(functionName())工作吗?,javascript,jquery,Javascript,Jquery,此代码按预期工作: $(function() { $("tr:odd").css("background-color","#dddddd"); }) 但这并不是: function temp() { $("tr:odd").css("background-color","#dddddd"); } $(temp()); 为什么?在第二个示例中,您正在传递temp函数的结果。你需要通过它的身体。因此,请使用以下命令: $(temp); 而不是 $(temp()); jQu
$(function() {
$("tr:odd").css("background-color","#dddddd");
})
但这并不是:
function temp() {
$("tr:odd").css("background-color","#dddddd");
}
$(temp());
为什么?在第二个示例中,您正在传递
temp
函数的结果。你需要通过它的身体。因此,请使用以下命令:
$(temp);
而不是
$(temp());
jQuery需要回调。尝试:
$(temp);
因为你应该写作
$(temp)
因为temp是一个回调函数
您在第二个代码段中所做的是
$(temp()) // => $(undefined) since temp doesnt return anything
$(function()
是$(document).ready
的快捷方式,基本上在页面加载时运行。
因此,在上面的解决方案中,加载时添加函数,而不是在下面的解决方案中添加函数
试试这个:
function temp() {
$("tr:odd").css("background-color","#dddddd");
};
$(function() {
temp();
});
我确信这两个函数都能按预期工作,这取决于您的期望。请澄清您的期望。temp是函数,temp()是执行函数的结果。$(temp())结果会立即执行temp,而不是在DOM就绪时执行temp,这正是您想要的comment@mihai它实际上应该是null,因为如果您查看jQuery代码,它返回null而不是undefinedright,应该返回undefined(函数temp),但是$()我想实际上返回空值。