简体   繁体   English

如何检查功能是否存在?

[英]How to check if function exist?

How to check if is function on jquery, but function is in another .js file? 如何检查jquery上是否有函数,但函数是否在另一个.js文件中?

validation.js: 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 . 这是假的,因为func付款在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. 它非常适合Blogger。

You can check if a function exists using window 您可以使用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: 如果您在payment.js中的函数是自包含函数的一部分,则需要将其设置为,以便窗口对象可以通过在自包含函数中添加它来“看到”它:

window.NameOfTheFunction = NameOfTheFunction;

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

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