简体   繁体   English

检查jQuery方法是否存在

[英]Check if jQuery method exists

Is it possible? 可能吗? No matter how, in Javascript or jQuery. 无论如何,在Javascript或jQuery中。

For example: $.isFunction($.isFunction()); 例如: $.isFunction($.isFunction());

Upd: But how to check method of a jQuery plugin? Upd:但是如何检查jQuery插件的方法? Sometimes it not ready at the moment of it call and generates error. 有时它在调用时没有准备好并产生错误。 Example: $.isFunction($().jqGrid.format) 示例: $.isFunction($().jqGrid.format)

To pass a function to another function, leave the () off: 要将函数传递给另一个函数,请关闭()

$.isFunction($.isFunction);   // true!

When you write () you are calling the function, and using the result it returns. 当你写()你正在调用该函数,并使用它返回的结果。 $.isFunction() with no argument returns false (because undefined isn't a function), so you are saying $.isFunction(false) , which is, naturally, also false . 没有参数的$.isFunction()返回false (因为undefined不是函数),所以你说$.isFunction(false) ,当然也是false

I wouldn't bother using isFunction merely to check for the existence of something, unless you suspect that someone might have assigned a non-function value to it for some reason. 我不isFunction只使用isFunction来检查某些东西的存在,除非你怀疑有人可能因某种原因为它分配了一个非函数值。 For pure existence-checking, use the in operator: 对于纯存在检查,请使用in运算符:

if ('isFunction' in $) { ...

Yes, 是,

jQuery.fn.exists = function(){return jQuery(this).length>0;}

if ($(selector).exists()) {
    // code........
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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