Adding function parameters using a single variable in jQuery
I was thinking the is it p开发者_如何学JAVAossible to pass a variable to function which is to be executed on clicking the button and the function is given by a variable.
Also the parameters of the functions could be more than one and so I separated them by ,
.
So is there a way that I can put the parameters into function using any jQuery plugin or a function. Please help me out, cause I'm confuse big time! Here is my current jQuery Code:
function Func (a,b){
alert(a+' | '+b);
}
var Parameters = 'cool,123';
var Function = Func;
$('button').click(Function);
Problem demo
Thanks in advance
You can use function.apply()
. Pass your list of parameters in as an array and you can even set a scope if you wish to do so:
function myFunc(a,b){
alert(a+", "+b);
}
var args = ["one", "two"];
var func = myFunc;
$('button').click(function(){
func.apply(this, args);
});
Is this what you're after?
function Func (a,b){
alert(a+' | '+b);
}
var Parameters = 'cool,123';
$('button').click(function() {
Func.apply(this, Parameters.split(","));
});
Demo: http://jsfiddle.net/6nJx7/14/
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/function/apply
You could pass your parameters as an array ..
function Func (a){
alert(a[0]+' | '+a[1]);
}
var Parameters = new Array(0,1);
var Function = Func;
$('button').click(Function(Parameters));
Here is another way to do it, I like this better myself because it is somewhat self documenting. Each of the "parameters" in the options list has a name.
This is a common design pattern in JavaScript libraries for options to a module.
function Func (c){
alert(c.a+' | '+c.b);
}
var Parameters = { a : "cool", b: 123 };
var Function = Func;
$('button').click(Parameters );
精彩评论