简体   繁体   中英

Jquery call function dynamically

I have a following scenario that I have to call a function on a jquery object dynamically. The code looks like this :

$('div[class]').each(function(){
    var class=$(this).attr('class');

    // I want to now check if that function with the name of class exists for jquery
    // object. I need help here.
    // if that function exists, i need to apply that function to the enumerated object.
});

I want to now check if that function with the name of class exists for jQuery object. I need help here. If that function exists, I need to apply that function to the enumerated object.

I'm writing this of the top of my head so it might not work, but try:

if(jQuery.isFunction(jQuery[class]))
     jQuery[class](this);

Edit: if the function is a jquery method then try with:

 if(jQuery.isFunction(jQuery.fn[class])) {
     jQuery.fn[class](this);
     jQuery(this)[class]();    // alternative call syntax
 }

使用$.isFunction(func)来确定func是否是函数。

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