Check if javascript function is a method for jQuery element

How do you detect if a function is a method for a jQuery element?

For example, $.fn.fadeInthis is a function:

    typeof $.fn.fadeIn === 'function' //true

However, I need a way to distinguish it from the regular non-jQuery method. The goal is to be able to pass the function as a parameter, and then call the function correctly.

The following is an example using a function with a name doItthat takes a jQuery element and a function applied to the element.

HTML example:

<h1>jQuery Function Test</h1>
<p class=t1>Highlight this line.</p>
<p class=t2>Hide this line.</p>

JavaScript example:

function doIt(elem, func) {
   if (func === 'a jQuery function')  //possible?
      func.apply(elem);
   else
      func(elem);
   }

function highlight(elem) {
   elem.css('background-color', 'gold');
   }

doIt($('p.t1'), highlight);
doIt($('p.t2'), $.fn.fadeOut);

Line # 2 needs JavaScript help.

Interactive version:

    http://jsfiddle.net/sxduwke9/

+4
source share
2

, , , ...

function doIt(elem, func, params) {
    if (typeof func === 'function')
        func.apply(elem, [elem].concat(params));
    else if (elem[func] && params instanceof Array)
        elem[func](params[0], params[1], params[2]);
    else if (elem[func])
        elem[func](params);
}

jsfiddle

+1

. if:

function doIt(elem, func) {
    func.apply(elem);
}

function highlight() {
    this.css('background-color', 'gold');
}

doIt($('p.t1'), highlight);
doIt($('p.t2'), $.fn.fadeOut);

, :

function doIt(elem, func) {
    var args = Array.prototype.slice.call(arguments, 2);
    func.apply(elem, args);
}

function highlight(color) {
    this.css('background-color', color);
}

doIt($('p.t1'), highlight, 'gold');
doIt($('p.t2'), $.fn.fadeOut);
+3

All Articles