问题
I have a function which I can not seem to add callback into.
function ajaxCartFormSubmitted(e) {
someotherfunctionsinside();
if (e)...
});
function test () {
console.log('abraka');
}
I try do do
function ajaxCartFormSubmitted(e, callback) {
someotherfunctionsinside();
if (e)...
if (callback) {
callback();
}
});
and then calling
ajaxCartFormSubmitted(test);
But I get Uncaught TypeError: callback is not a function. What is the problem? I use jquery 1.3 and cannot upgrade. Thank you.
回答1:
You have two problems.
1
There are two arguments e
and callback
. You have to pass them both if you want the callback since that's your 2nd argument.
Like this: ajaxCartFormSubmitted(event, test)
You can't only pass the 2nd argument and skip the first one. if you need to do this, write a different function.
2
if it gets called as ajaxCartFormSubmitted(event, 'foo')
or ajaxCartFormSubmitted(event, true)
then neither 'foo'
nor true
are functions. you just need to check that the type of callback
is actually a function before you run it
function ajaxCartFormSubmitted(e, callback) {
someotherfunctionsinside();
if (e) {
...
}
if (callback && typeof callback === 'function') {
callback();
}
});
if that's still not working, add a console.log
in there so you can debug it and see what it is.
console.log(typeof callback, callback)
回答2:
But I get Uncaught TypeError: callback is not a function. What is the problem?
The problem is that you haven't passed ajaxCartFormSubmitted
two arguments, you've only passed it one, which it receives as the parameter e
(the first parameter). The callback
parameter will be undefined
when you do that.
Either pass it two arguments, or change the function so it only expects one.
What the function expects:
function ajaxCartFormSubmitted(e, callback) {
// First parameter --^ ^^^^^^^^--- second parameter
What you're sending it:
ajaxCartFormSubmitted(test);
// ^^^^------ First (only) argument
来源:https://stackoverflow.com/questions/56347115/add-callback-to-functione-uncaught-typeerror-callback-is-not-a-function