jQuery isFunction检查错误“函数未定义” [英] jQuery isFunction check error "function is not defined"

查看:282
本文介绍了jQuery isFunction检查错误“函数未定义”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在试图运行它之前,我想检查函数是否存在。这里是我的代码:

$ $ p $ $ code if($ .isFunction(myfunc())){
console.log(函数存在,运行!!!);
}

但是,当函数不可用时,我得到错误:


myfunc未定义


我该怎么办检测?这是我的工作测试: http://jsfiddle.net/3m3Y3/

(),你实际上试图在你的第一行中直接运行它。解决方案 / p>

相反,您应该只使用函数名称而不运行它:

  if($ .isFunction(myfunc)){

然而 - If myfunc 不是一个函数,也不是任何其他已定义的变量,但它仍然会返回一个错误,尽管它是不同的。像 myfunc没有定义



您应该检查名称是否存在,然后检查它是否为函数,像这样:

  if(typeof myfunc!=='undefined'&& $ .is.Function(myfunc)){ 

工作示例: http://jsfiddle.net/sXV6w/


I want to do a check whether a function exist or not before trying to run it. Here is my code:

if ($.isFunction(myfunc())) {
    console.log("function exist, run it!!!");
}

However, when the function is not available I got the error:

myfunc is not defined

How can I do the detection? Here is my working test: http://jsfiddle.net/3m3Y3/

解决方案

By putting () after the function name, you're actually trying to run it right there in your first line.

Instead, you should just use the function name without running it:

if ($.isFunction(myfunc)) {

However - If myfunc is not a function and is not any other defined variable, this will still return an error, although a different one. Something like myfunc is not defined.

You should check that the name exists, and then check that it's a function, like this:

if (typeof myfunc !== 'undefined' && $.isFunction(myfunc)) {

Working example here: http://jsfiddle.net/sXV6w/

这篇关于jQuery isFunction检查错误“函数未定义”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆