Passing selectors as function parameters in jQuery

RedGiant

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.

T.J. Crowder

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related