Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检查JavaScript函数是否是jQuery元素的方法_Javascript_Jquery_Function_Instanceof_Typeof - Fatal编程技术网

检查JavaScript函数是否是jQuery元素的方法

检查JavaScript函数是否是jQuery元素的方法,javascript,jquery,function,instanceof,typeof,Javascript,Jquery,Function,Instanceof,Typeof,如何检测函数是否是jQuery元素的方法 例如,$.fn.fadeIn是一个函数: typeof$.fn.fadeIn==='function'//true 但是,我需要一种方法来区分它与常规的非jQuery方法。目标是能够将函数作为参数传递,然后正确调用该函数 下面是一个使用名为doIt的函数的示例,该函数接受jQuery元素和要应用于该元素的函数 HTML示例: <h1>jQuery Function Test</h1> <p class=t1>Highl

如何检测函数是否是jQuery元素的方法

例如,
$.fn.fadeIn
是一个函数:

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

但是,我需要一种方法来区分它与常规的非jQuery方法。目标是能够将函数作为参数传递,然后正确调用该函数

下面是一个使用名为
doIt
的函数的示例,该函数接受jQuery元素和要应用于该元素的函数

HTML示例:

<h1>jQuery Function Test</h1>
<p class=t1>Highlight this line.</p>
<p class=t2>Hide this line.</p>
JavaScript的第2行需要帮助

互动版本:


否。但您可以完全删除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);

这里有一个结合字符串参数思想的解决方案,检查对象上是否存在该方法,并支持参数

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

或者在

上,一种方法是迭代传入的jQuery对象的所有属性,并测试
elem[prop]==func
。不过效率不是很高。不如传递一个字符串
“fadeOut”
,而不是
$。fn.fadeOut
。然后只需执行以下操作:
if(typeof func==“string”)elem[func]();else-func(elem)
@cookiemonster,这是一个很好的选择,但在我的实际代码中,我已经接受字符串并将其转换为函数。我想我可以试试:
(typeof func==“string”&&elem[func])
也许这是最好的解决方案。然而,在我的例子中,回调函数实际上是由库的用户编写的,因此我可能只需要添加一个选项来显式声明函数是否是jQuery方法。
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);
}