2

Fiddle Example

Can I pass selectors other than $(this) selector as function parameters?

What I mean is that the selectors (#Aarea and Barea) I want to pass are the ones that I want to append some HTML content to.

function info(a){
  var source = $(this).data('source')
  $(a).html(source)
  console.log(source);
}

$('#one').click(info('#Aarea'))
$('#two').click(info('#Barea'))

<button data-source="AAA" id='one'>Button</button>
<div id="Aarea"></div>
<div id='Barea'></div>
<a href='#' data-source='BBB' id='two'>Click</a>

But it doesn't work unless I don't use the parameters and specify those selectors in the function.

AstroCB
  • 12,337
  • 20
  • 57
  • 73
RedGiant
  • 4,444
  • 11
  • 59
  • 146

4 Answers4

10

What your code:

$('#one').click(info('#Aarea'))

...is doing is calling info and passing its return value into click, exactly like foo(bar()) calls bar and passes its return value into foo.

What you want to give click is a function to call. In your case, the simplest way is to use a wrapper function:

$('#one').click(function() {
    info(this, '#Aarea');
});

...and update info to accept the element as an argument:

function info(element, a){
  var source = $(element).data('source')
  $(a).html(source)
  console.log(source);
}

Updated Fiddle

Alternately, you can use Function#call to call your original info without changing it:

$('#one').click(function() {
    info.call(this, '#Aarea');
});

Function#call calls a function, setting this during the function call to the first argument you give it (and then passing along any other arguments you give to it).

Updated Fiddle

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

I think your problem is that you're passing the evaluated function into your click handler.

The proper format is something more like this:

$('#one').click(function(){ info('#Aarea'); })
$('#two').click(function(){ info('#Barea'); })

Here's a fiddle with working code -http://jsfiddle.net/2548hkvg/

Alternatively, you could define the target area as a data attribute as well, and only have one function, seen in this fiddle - http://jsfiddle.net/k42ahykb/

In the code for that, we're defining info as our function expression that we pass to the click handler, and this is properly retained.

function info(e){
  var source = $(this).data('source');
  var target = $(this).data('target');
  $(target).html(source)
  console.log(source);
}

$('#one').click(info)
$('#two').click(info)
iabw
  • 1,108
  • 1
  • 9
  • 24
2
$('#one').click(info('#Aarea'))

You are calling the function here, so the result passed to .click() is undefined. Like @iabw said, you need to wrap it in a function expression so the click event can invoke info() successfully.

David G
  • 94,763
  • 41
  • 167
  • 253
1

Just passthrough this from onclick function to info.

$('#one').click(function(){ info.call(this, '#Aarea'); })
$('#two').click(function(){ info.call(this, '#Barea'); })
Mark.Ablov
  • 857
  • 6
  • 6