在这个问题上我一直在用头撞墙,但我似乎不太明白。我知道那里还有很多其他非常相似的问题,我几乎看过所有这些问题,但似乎没有一个能找到我正在寻找的答案(但话又说回来,我可能是瞎子今天)。
所以我有一个 JavaScript 函数,我将一个函数作为参数传入以执行回调。我的函数中有一个参数,所以当我执行回调时,我传入的参数需要在调用回调时跟进。
但是,当我添加第二个参数时,该值始终未定义。
示例代码:
<div style="padding: 15px;">
<a href ="#" onclick="FirstFunction('first param');">test</a>
</div>
//call the first function from the click event and pass in the value
function FirstFunction(param1) {
//call my process function, but pass in a function as a parameter with the value from param1
myProcessFunction(function(){SecondFunction(param1)});
return false;
}
function SecondFunction(param1, param2) {
alert(param1 + ', ' + param2);
}
function myProcessFunction(callback) {
if (typeof callback == 'function') {
//call my passed in function, return the original values, along with a new value into my "SecondFunction"
callback(this, 'second param');
}
}
如有任何帮助,我们将不胜感激。
我试过:
callback.call(this, 'param 2')
callback(arguments, 'param 2')
callback.call(arguments, 'param 2')
可能还有大约 20 种其他组合...所以我现在正在猜测。
这是我的 jsFiddle:
编辑
谢谢 Jani,这是 jsFiddle 中的一个有效解决方案: http://jsfiddle.net/FVsDK/9/
最佳答案
错误是因为你的回调有点乱:)
myProcessFunction(function(){SecondFunction(param1)});
这会调用带有回调函数的 myProcessFunction function() { ... }
因此,在 myProcessFunction 中,callback(this, 'second param');
正在调用上面的函数,它根本不带任何参数。
如果你想让 secondFunction 从 myProcessFunction 获取参数,你必须传递它而不是你的匿名回调:
我的ProcessFunction(SecondFunction)
在这里,SecondFunction 的参数将是 this
和 'second param'
。
或者如果你想将 param1 传递给它,你也可以这样做:
myProcessFunction(function(a, b) { SecondFunction(param1, a, b); })
这里,SecondFunction 的参数将是 param1、this
和 'second param'
的值。
关于JavaScript 回调函数不处理传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10740101/