jQuery test for whether an object has a method?

后端 未结 6 1009
一整个雨季
一整个雨季 2020-12-08 11:09

Is it possible to test whether a jQuery object has a particular method? I\'ve been looking, but so far without success. Thanks!

相关标签:
6条回答
  • 2020-12-08 11:12

    try

    if ($.fn.method) {
        $('a').method(...);
    }
    

    or

    if ($.method) {
        $.method(...);
    }
    
    0 讨论(0)
  • 2020-12-08 11:13

    This should work:

    if (!!$.prototype.functionName)
    
    0 讨论(0)
  • 2020-12-08 11:13

    You should be able to look for undefined

    if( typeof jQuery("*").foo === "undefined" ){
      alert("I am not here!");
    }
    
    0 讨论(0)
  • 2020-12-08 11:23
    //Simple function that will tell if the function is defined or not
    function is_function(func) {
        return typeof window[func] !== 'undefined' && $.isFunction(window[func]);
    }
    
    //usage
    
    if (is_function("myFunction") {
            alert("myFunction defined");
        } else {
            alert("myFunction not defined");
        }
    
    0 讨论(0)
  • 2020-12-08 11:28

    Because jQuery methods are prototype into a jQuery object, you can test it from the prototype object.

    if( $.isFunction( $.fn.someMethod ) ) {
        // it exists
    }
    

    This uses the jQuery.isFunction()[docs] method to see if $.fn.someMethod is indeed a function. (In jQuery jQuery.fn is a reference to the prototype object.)

    0 讨论(0)
  • 2020-12-08 11:31

    this worked for me

    if (typeof myfunctionname === 'function')
    
    0 讨论(0)
提交回复
热议问题