views:

73

answers:

3

Is it possible to pass arguments to click or submit 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?

+1  A: 

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"&gt;Google&lt;/a&gt;
<a rel="bar" href="http://stackoverflow.com"&gt;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]);
  }
});
Jonathan Sampson
@Jonathan Sampson thanks that is interesting, what if I wanted to pass more than one argument? 2 lets say
Gandalf StormCrow
@Gandalf: Check out my updated portion.
Jonathan Sampson
+1 I rarely need to pass information to the click handler that isn't contained in the element already! Also of note, are the new `data-` prefixed attributes in HTML5 for holding random data.
Doug Neiner
+1  A: 

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

Doug Neiner
+1 Another great method!
Jonathan Sampson
A: 

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.

sth