简体   繁体   English

动态调用JavaScript函数

[英]Call a javascript function dynamically

I have some functions defined inside a array like this. 我在这样的数组中定义了一些函数。

checkInputType : function(sel){
 alert($(sel).prop('type'));
},
checkSelect : function(el){
 .......
},
.....

And I can call it like this options.checkInput($(this)); 我可以这样称呼它options.checkInput($(this)); . This is working. 可以了
Now I want to call any of those defined functions dynamically. 现在,我想动态调用这些已定义函数中的任何一个。 So I have this array with the function names in it. 所以我有一个带有函数名称的数组。

var elmType2Func = {'input' : 'checkInput', 'select' : 'checkSelect', 'textarea' : 'checkTextarea'};

Now looping through all elements inside a form I want to call the right function for each element( elmType2Func array with element as a key and function name as a value ). 现在遍历表单内的所有元素,我想为每个元素调用正确的函数( elmType2Func数组,其中element作为键函数名称作为value )。

var element = $(this).prop('tagName').toLowerCase();

I cannot call like this - options.elmType2Func[element]($(this)); 我不能这样称呼options.elmType2Func[element]($(this)); I know this is not the right way to call this function. 我知道这不是调用此函数的正确方法。
Can anybody help me with this. 谁能帮我这个忙。

You need to store functions, not their names: 您需要存储函数,而不是它们的名称:

var elmType2Func = {'input' : checkInput, 'select' : checkSelect, 'textarea' : checkTextarea};

http://jsfiddle.net/hmb25/ http://jsfiddle.net/hmb25/

If the functions are already members of some object, like: 如果函数已经是某个对象的成员,例如:

var options = {
     checkInput: function() {...},
     checkSelect: function() {...},
}

then you can keep strings in elmType2Func : 那么您可以将字符串保留在elmType2Func

var elmType2Func = {'input' : 'checkInput', 'select' : 'checkSelect', 'textarea' : 'checkTextarea'};

and use double indirection to refer to them: 并使用双重间接引用来引用它们:

var tag = $(this).prop('tagName').toLowerCase();
var fun = options[elmType2Func[tag]];

gives you a reference to the function. 给您该功能的参考。

Rather than putting a string for the name put the function 而不是为名称放置字符串,而是将函数

var elmType2Func = {
    'input' : checkInput,
    'select' : checkSelect, 
    'textarea' : checkTextarea,
    'submit' : function (arg) { ... }
};
 options.elmType2Func[element]($(this)); 

That is accessing the property with the literal name elmType2Func on the object - you want to use bracket notation here as well: 那就是在对象上使用文字名称elmType2Func访问属性-您也想在这里使用括号表示法:

options[elmType2Func[element]]($(this));

Alternatively, you might not use elmType2Func as a property name lookup table, but to look up the functions directly: 或者,您可能不使用elmType2Func作为属性名称查找表,而是直接查找功能:

var elmType2Func = {
    'input' : options.checkInput,
    'select' : options.checkSelect, 
    'textarea' : options.checkTextarea
};
elmType2Func[element]($(this));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM