1
jQuery.fn.testeee = function(_msg)
{
    alert(_msg);
    $(this[0]).overlay({ 
        onBeforeLoad: function() 
        {
            alert(_msg);
        }
    }).load();
};
$("#popup").testeee ('test');
$("#popup").testeee ('another_test');

这显示:

  • 测试
  • 测试
  • 另一个测试
  • 测试

分配给 onBeforeLoad 的匿名函数中的 alert() 一直显示“测试”。我试试这个:

jQuery.fn.testeee = function(_msg)
{
    alert(_msg);
    $(this[0]).overlay({ 
        onBeforeLoad: static_func(_msg)
    }).load();
};
function static_func(_msg) 
{
    alert(_msg);
}
$("#popup").testeee ('test');
$("#popup").testeee ('another_test');

它工作得很好。它显示:

  • 测试
  • 测试
  • 测试
  • 测试

任何人都知道为什么会发生这种情况?

4

1 回答 1

2

如果您创建这样的对象:

{
   onBeforeLoad: static_func(_msg)
}

它没有指定要调用的函数,而是立即调用该函数并将返回值存储在对象中。

要指定要调用的函数,只需使用函数名称:

{
   onBeforeLoad: static_func
}

如果你想用你自己指定的参数调用函数,你必须通过将变量包装在匿名函数中来创建一个包含变量的闭包:

{
   onBeforeLoad: function() { static_func(_msg) }
}
于 2009-09-09T05:30:53.057 回答