检查函数是否动态存在
我需要一个函数来检查 jQuery 中的函数是否存在,如果存在,则应该调用该函数。如果我使用下面的代码和一个简单的名称,它可以工作,但如果我想动态检查函数是否存在,它就不起作用。有人有想法吗?
function homeController() {
console.log('in the homecontroller');
}
$('div[class="view"]').each(function() {
$('#' + this.id).live('pageshow', function() {
var func = this.id + 'Controller';
if($.isFunction(func)) {
console.log('jquery exists');
}
});
});
I need a function to check whether a function in jQuery exists and if that's true this function should be called. If I use below code with an simple name it works, but if i want to check dynamically whether a function exists it doesn't work. Have anybody an idea?
function homeController() {
console.log('in the homecontroller');
}
$('div[class="view"]').each(function() {
$('#' + this.id).live('pageshow', function() {
var func = this.id + 'Controller';
if($.isFunction(func)) {
console.log('jquery exists');
}
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Reflection-java 还可以用于动态检查方法、字段或类是否存在。
欲了解更多信息:
如何检查方法在运行时是否存在Java?
Reflection-java can also be used to check whether a method or a field or a class exists or not, dynamically.
for more information:
How To Check If A Method Exists At Runtime In Java?
仅当函数存在时才执行回调。您可以从此函数中提取该行并在任何地方使用它。
This only executes the callback if the function exists. You can pull that line from this function and use it anywhere.
使用
jQuery.isFunction()
方法检查对象是否是一个函数还是不是一个函数。Use the
jQuery.isFunction()
method to check whether an object is a function or not.我认为您需要为此使用
eval
,因为您的func
是一个字符串。I think that you need to use
eval
for that, because yourfunc
is a string.$.isFunction - “确定传递的参数是否是 Javascript 函数对象”。显然,您正在传递一个字符串。
如果您想检查 jQuery 插件而不是使用
And 对于一般 JavaScript 函数 -
$.isFunction - "Determine if the argument passed is a Javascript function object". Obviously, you are passing a string.
If you wish to check for jQuery plugin than use
And for general JavaScript function -
您需要弄清楚您的函数位于哪个范围(或者换句话说,哪个对象是您的函数属性),然后使用
将所需函数的名称转换为当前范围内对该函数的引用。
当然,这是假设您的函数实际上在某个范围内。
因此,如果您的
homeController()
函数已在全局范围内声明,则它将成为window.
全局对象的属性。但是,如果它们刚刚在其他某个闭包中被声明为内部函数,那么它们就不会拥有内部函数。
You need to figure out which scope your function is in (or in other words, which object are your functions properties of), and then use
to convert the name of the required function into a reference to that function within the current scope.
That assumes, of course, that your functions are actually in some scope.
So if your
homeController()
function has been declared in global scope, it will be a property of thewindow.
global object.However if they've just been declared as an inner function within some other closure they won't have one.