简体   繁体   中英

How to check if function exist?

How to check if is function on jquery, but function is in another .js file?

validation.js:

if ($.isFunction('payment')) {
    $('[data-numeric]').payment('restrictNumeric');
    $('.cc-number').payment('formatCardNumber');
    $('.cc-exp').payment('formatCardExpiry');
    $('.cc-cvc').payment('formatCardCVC');
}

this is false because func payments is in the payments.js .

Try like this

if (typeof payment === "function")
{
  // Do something
}

problem is solved. its works:

if ($.fn.payment) {
    //do something
}

Try to check like as follows,

 if (typeof payment !== 'undefined' && $.isFunction(payment)) {
    $('[data-numeric]').payment('restrictNumeric');
    $('.cc-number').payment('formatCardNumber');
    $('.cc-exp').payment('formatCardExpiry');
    $('.cc-cvc').payment('formatCardCVC');
 }
if (typeof yourFunctionName == 'function') { 
  yourFunctionName(); 
}

It works perfect for Blogger.

You can check if a function exists using window

For example

var fn = window['NameOfTheFunction']; 
if(typeof fn === 'function') {
    doSomething();
}

If your function in payment.js is part of a self contained function, you need to set it to so the window object can "see" it by adding this in your self contained function:

window.NameOfTheFunction = NameOfTheFunction;

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