sorin
sorin

Reputation: 461

Passing a jquery method as a parameter into a function?

Is it possible to pass a jQuery method as a parameter into a function , for example:

function set_action(a,b)
{
  $(a).b;
}

$(function(){
    $('#div_id1').click(function(){
        set_action('#div_id2','hide()');
    });
});

?

Upvotes: 2

Views: 197

Answers (2)

mhps
mhps

Reputation: 166

function set_action(a,b) {
   $(a)[b]();
}


$('#hello').click(function(){
  set_action('#bye','hide');
});

See it working.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816324

You can access any property of an object with a string using bracket notation:

var foo = {
   bar: 5
};

console.log(foo['bar']);

So you could do:

function set_action(a,b) {
  $(a)[b]();
}

set_action('#div_id2','hide');

Note that this will throw an error if the object does not have a callable property with that name.

Upvotes: 6

Related Questions