passing arguments to click or submit function
Is it possible to pass arguments to click or submi开发者_如何学Ct function like :
$("#example").click(function()
{
var myVar = x; // refering to x as passed argument
});
Maybe function inside a function ?
function Func(){
$("#example").click(function()
{
var myVar = x;
});
}
Maybe something like calling Func()('33');
will this pass the 33 to the click function, is it possible after all?
Without knowing what you want to accomplish, its hard to tell you what to do. Many times when a similar need arrises, it has to do with passing an ID to the function. There are a few ways to handle this, but lets look at one:
var $a = $('a'), // Pretend we have three `a` elements
keys = ['apple','orange','grape'];
$a.each(function(i,el){
var val = keys[i]; // Declare a variable to this scope using `var` and set it to the value you want:
$(this).click(function(){
alert(val);
});
});
Now, if you click the first a
it alerts apple
, the second orange
, and the third grape
. By declaring a variable in the function scope using var
allows that particular click to know the correct value.
Demo of this working
This would depend on what "arguments" you want to pass. Much of this is often times handled with some simple attributes on the elements themselves:
<a rel="foo" href="http://google.com">Google</a>
<a rel="bar" href="http://stackoverflow.com">Stack Overflow</a>
Which would use the rel
attribute as the "argument." You could access it from the $.click()
:
$("a").click(function(){
switch( $(this).attr("rel") ) {
case "foo":
// do x
break;
case "bar":
// do y
break;
}
});
As you could imagine, this could be extended to include attributes like:
rel="foo,2,max"
Where the value of rel
will be .split()
within the click-method giving us an array of "arguments" to consider in our logic.
$("a").click(function(){
var arguments = $(this).attr("rel").split(",");
for (var i = 0; i < arguments.length; i++) {
alert(arguments[i]);
}
});
If you want to access parameters passed to Func
in the click function, you can just do it:
function Func(x) {
$("#example").click(function()
{
var myVar = x;
});
}
The inner function definition builds a closure, and the local variables of the outer function are kept in the scope of that closure and can still be accessed, even if the outer function already finished.
精彩评论