将参数传递给作为参数传递给jQuery函数的函数

将函数名称作为参数传递给另一个函数似乎对我不起作用。

我已经尝试过我能找到的每篇文章中的每一个变体。 目前,我在一个js文件中有这个:

function callThisPlease (testIt){ alert(testIt); } $(document).ready(function () { $.fn.pleaseCallTheOtherFunction('callThisPlease'); }); 

我在另一个:

 $(document).ready(function () { $.fn.pleaseCallTheOtherFunction = function(functionName){ window[functionName].apply('works'); } }); 

chrome console表示Uncaught TypeError: Cannot call method 'apply' of undefined

请帮忙。 提前谢谢了!

如果window上的方法未定义,则表示您的函数不是全局的。 使它成为一个全球function。


此外,你可以摆脱.apply 。 目前,您正在传递'works'作为this值。

 window[functionName]('works'); 

jsFiddle演示

建立

首先,您需要设置pleaseCallTheOtherFunction方法,如下所示:

 $.fn.pleaseCallTheOtherFunction = function(otherFunction) { if ($.isFunction(otherFunction)) { otherFunction.apply(this, ['works']); } }; 

用法

然后你将要创建你的’替换’函数(委托),然后不带引号调用它,如下所示:

 function callThisPlease (testIt){ alert(testIt); } $(document).ready(function () { $().pleaseCallTheOtherFunction(callThisPlease); }); 

另外

你可以编写一个内联函数:

 $(document).ready(function () { $().pleaseCallTheOtherFunction(function(testIt) { alert(testIt); }); });