36

可能重复:
jQuery 测试对象是否有方法?

我想在调用 javascript 之前设置函数是否存在你能帮我如何做到这一点并应用在这个脚本上吗

$(document).ready(function() {
   $(".cs-text-cut").lettering('words');
});
4

4 回答 4

96

我假设你想要检查并确保它lettering存在,试试这个:

http://api.jquery.com/jQuery.isFunction/

这是一个例子:

if ( $.isFunction($.fn.lettering) ) {
    $(".cs-text-cut").lettering('words');
}
于 2012-12-01T07:01:15.570 回答
23

Use this to check if function exists.

<script>
if ( typeof function_name == 'function' ) { 
        //function_name is a function
}
else
{
 //do not exist
}
</script>
于 2012-12-01T07:06:34.447 回答
7

If it's the lettering function you want to test for, you can do so like this;

$(document).ready(function() {
    var items = $(".cs-text-cut");
    if (items.lettering) {
        items.lettering('words');
    }
});

Or, if you want to make absolutely sure items.lettering is a function before attempting to call it, you can do this:

$(document).ready(function() {
    var items = $(".cs-text-cut");
    if (typeof items.lettering === "function") {
        items.lettering('words');
    }
});

Or, if you really don't control the environment so you don't really know if the lettering function call is going to work or not and might even throw an exception, you can just put an exception handler around it:

$(document).ready(function() {
    try {
        $(".cs-text-cut").lettering('words');
    } catch(e) {
        // handle an exception here if lettering doesn't exist or throws an exception
    }
});
于 2012-12-01T07:04:24.833 回答
0

typeof $({}).lettering == 'function'或者$.isFunction($({}).lettering)应该返回一个布尔值是否可用。

于 2012-12-01T07:30:43.190 回答