简体   繁体   中英

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

?

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.

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


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

See it working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM