JQuery check if variable is function
This question already has an answer here:
In your example, to get a reference to the testFunction
if it is in scope, you can use eval
. Yes, I said it, eval
, so you have to know that the string could be manipulated by the user to run malicious code if you don't sanitize it for function names;
var testController = function() {
alert('123');
}
$(function() {
$('[mfour]').each(function(e, t) {
var a = eval($(t).attr('mfour'));
console.log($.isFunction(testController));
console.log($.isFunction(a));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div mfour="testController">Hello</div>
Try using window[varname]
- assuming the function is in global scope
like this
DEMO
var testController = function() {
alert('123');
}
$(function() {
$('[mfour]').each(function(e, t) {
var a = $(t).attr('mfour');
console.log($.isFunction(testController));
console.log($.isFunction(window[a]));
console.log(typeof window[a] === "function");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div mfour="testController">Hello</div>
To check if the variable is a function just add a check
typeof variableName
It will return the type of variable.
Dude..
If possible, add your function to an object. Like below
var obj = {
testController: function(){
alert('123');
}
};
$(function() {
$('[mfour]').each(function(e, t) {
var a = $(t).attr('mfour');
console.log($.isFunction(obj[a]));
})
});
链接地址: http://www.djcxy.com/p/94840.html
上一篇: 这种定义JS对象的方式有什么用处吗?
下一篇: JQuery检查变量是否是函数