如何检查功能是否存在?

时间:2015-05-13 13:12:56

标签: javascript jquery

如何检查jquery上是否有函数,但函数是否在另一个.js文件中?

validation.js:

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

这是假的,因为func付款在payments.js。

4 个答案:

答案 0 :(得分:25)

试试这个

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

答案 1 :(得分:16)

问题解决了。它的作品:

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

答案 2 :(得分:8)

尝试检查如下,

Team _team1 = new Team(name: "Fiorentina",club: true) 
Team _team2 = new Team(name:"Juventus",club: true)
_team1.save()

_team2 .save()


Result a = new Result(goals1: 1, goals2: 0) 
Result b = new Result(goals1: 0, goals2: 2) 
Result c = new Result(goals1: 1, goals2: 0) 
Result d = new Result(goals1: 5, goals2: 4)
a.save()

b.save()

c.save()

d.save()

SingleMatch match1 = new SingleMatch(team1: _team1, team2: _team2, startDate: new Date(), firstHalfResult: a, secondHalfResult: b, extraTimeResult: c, penaltyResult: d)

match1.save();

答案 3 :(得分:1)

您可以使用window

检查某个功能是否存在

例如

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

如果您在payment.js中的函数是自包含函数的一部分,则需要将其设置为以便窗口对象可以通过在自包含函数中添加它来“看到”它:

window.NameOfTheFunction = NameOfTheFunction;
相关问题