我将mainSubmitHandler
用于多个页面,如果有必要,我愿意将其定义为全局变量。但是,mainSubmitHandler
需要进行一些调整,我正在使用subSubmitHandler
处理此问题。我没有将subSubmitHandler
作为另一个全局变量,而是如何将其作为agrument传递给mainSubmitHandler
?
var mainSubmitHandler=function(form) {
//do a bunch of stuff
subSubmitHandler(form);
};
var subSubmitHandler=function(form) {
//do some stuff
};
// uses jQuery validation plugin
var validator=$("#form1").validate({
rules: {},
messages: {},
submitHandler: mainSubmitHandler
});
答案 0 :(得分:3)
您可以在此处使用bind
。
bind
包含一个函数引用,允许您将范围和变量传递给目标函数:
function.bind(thisArg [,arg1 [,arg2 [,...]]])
参数:
来源MDN
var mainSubmitHandler=function(form, callback) {
//do a bunch of stuff
if (typeof(callBack) != "undefined" && Object.prototype.toString.call(callBack) === "[object Function]") //sanity check. Check if callback is truly a function and exists.
{
callback(form);
}
};
var subSubmitHandler=function(form) {
//do some stuff
};
// uses jQuery validation plugin
var validator=$("#form1").validate({
rules: {},
messages: {},
submitHandler: mainSubmitHandler.bind(null, form, subSubmitHandler); //first argument is set to null. This passes the this argument of the targeted function.
});
答案 1 :(得分:1)
将该函数作为附加参数传递:
var mainSubmitHandler=function(form, secondFunction) {
//do a bunch of stuff
secondFunction(form);
};
mainSubmitHandler(form, subSubmitHandler);
这是你的意思吗?
您可以将无限的参数传递给函数,所有这些参数都是可选的。你甚至可以这样做:
function doSomething(){ // not defining any arguments
console.log( arguments); // will output everything you passed the function
}
doSomething( "Hello", someOtherFunction );
这也有效:
function doSomething(arg1, arg2){ // defining 2 arguments, but will accept more if given
console.log( arguments); // will output everything you passed the function
}
doSomething( "First", "Second", someFunction, "third");
这就是为什么许多严格的人讨厌Javascript,为什么我喜欢它=)