[英]Call a javascript function dynamically
我在这样的数组中定义了一些函数。
checkInputType : function(sel){
alert($(sel).prop('type'));
},
checkSelect : function(el){
.......
},
.....
我可以这样称呼它options.checkInput($(this));
。 可以了
现在,我想动态调用这些已定义函数中的任何一个。 所以我有一个带有函数名称的数组。
var elmType2Func = {'input' : 'checkInput', 'select' : 'checkSelect', 'textarea' : 'checkTextarea'};
现在遍历表单内的所有元素,我想为每个元素调用正确的函数( elmType2Func数组,其中element作为键 , 函数名称作为value )。
var element = $(this).prop('tagName').toLowerCase();
我不能这样称呼options.elmType2Func[element]($(this));
我知道这不是调用此函数的正确方法。
谁能帮我这个忙。
您需要存储函数,而不是它们的名称:
var elmType2Func = {'input' : checkInput, 'select' : checkSelect, 'textarea' : checkTextarea};
如果函数已经是某个对象的成员,例如:
var options = {
checkInput: function() {...},
checkSelect: function() {...},
}
那么您可以将字符串保留在elmType2Func
:
var elmType2Func = {'input' : 'checkInput', 'select' : 'checkSelect', 'textarea' : 'checkTextarea'};
并使用双重间接引用来引用它们:
var tag = $(this).prop('tagName').toLowerCase();
var fun = options[elmType2Func[tag]];
给您该功能的参考。
而不是为名称放置字符串,而是将函数
var elmType2Func = {
'input' : checkInput,
'select' : checkSelect,
'textarea' : checkTextarea,
'submit' : function (arg) { ... }
};
options.elmType2Func[element]($(this));
那就是在对象上使用文字名称elmType2Func
访问属性-您也想在这里使用括号表示法:
options[elmType2Func[element]]($(this));
或者,您可能不使用elmType2Func
作为属性名称查找表,而是直接查找功能:
var elmType2Func = {
'input' : options.checkInput,
'select' : options.checkSelect,
'textarea' : options.checkTextarea
};
elmType2Func[element]($(this));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.