Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing selectors as function parameters in jQuery [duplicate]

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.

like image 805
RedGiant Avatar asked Mar 01 '26 03:03

RedGiant


2 Answers

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

like image 113
T.J. Crowder Avatar answered Mar 02 '26 15:03

T.J. Crowder


$('#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.

like image 39
David G Avatar answered Mar 02 '26 16:03

David G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!