可能重复:
jQuery 测试对象是否有方法?
我想在调用 javascript 之前设置函数是否存在你能帮我如何做到这一点并应用在这个脚本上吗
$(document).ready(function() {
$(".cs-text-cut").lettering('words');
});
可能重复:
jQuery 测试对象是否有方法?
我想在调用 javascript 之前设置函数是否存在你能帮我如何做到这一点并应用在这个脚本上吗
$(document).ready(function() {
$(".cs-text-cut").lettering('words');
});
我假设你想要检查并确保它lettering
存在,试试这个:
http://api.jquery.com/jQuery.isFunction/
这是一个例子:
if ( $.isFunction($.fn.lettering) ) {
$(".cs-text-cut").lettering('words');
}
Use this to check if function exists.
<script>
if ( typeof function_name == 'function' ) {
//function_name is a function
}
else
{
//do not exist
}
</script>
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
}
});
typeof $({}).lettering == 'function'
或者$.isFunction($({}).lettering)
应该返回一个布尔值是否可用。