2

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()');
    });
});

?

2
  • eval the code if you want to do it that way eval("$('"+a+"')."+b); Commented Dec 29, 2011 at 19:08
  • 2
    Don't use eval()!!! Stay away from eval(). Its extremely inefficient!!! Commented Dec 29, 2011 at 19:10

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You can check to see if the object has a callable property using $.fn.hasOwnProperty(b) (when checking jQuery objects, use $.fn), or typeof $(a)[b] === 'function' or b in $(a).
0
function set_action(a,b) {
   $(a)[b]();
}


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

See it working.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.