如何在 Javascript 中调用动态命名的方法? [英] How do I call a dynamically-named method in Javascript?
问题描述
我正在动态创建一些 JavaScript,这些 JavaScript 将在构建网页时插入到网页中.
I am working on dynamically creating some JavaScript that will be inserted into a web page as it's being constructed.
JavaScript 将用于根据另一个 listbox
中的选择来填充 listbox
.当一个listbox
的选择改变时,它会根据listbox
的选择值调用一个方法名.
The JavaScript will be used to populate a listbox
based on the selection in another listbox
. When the selection of one listbox
is changed it will call a method name based on the selected value of the listbox
.
例如:
Listbox1
包含:
颜色
形状
如果选择了Colours
,那么它将调用一个populate_Colours
方法来填充另一个listbox
.
If Colours
is selected then it will call a populate_Colours
method that populates another listbox
.
澄清我的问题:如何在 JavaScript 中进行 populate_Colours
调用?
To clarify my question: How do I make that populate_Colours
call in JavaScript?
推荐答案
假设 populate_Colours
方法在全局命名空间中,您可以使用以下代码,它利用了所有对象属性可能就好像对象是一个关联数组一样访问,并且所有全局对象实际上都是 window
宿主对象的属性.
Assuming the populate_Colours
method is in the global namespace, you may use the following code, which exploits both that all object properties may be accessed as though the object were an associative array, and that all global objects are actually properties of the window
host object.
var method_name = "Colours";
var method_prefix = "populate_";
// Call function:
window[method_prefix + method_name](arg1, arg2);
这篇关于如何在 Javascript 中调用动态命名的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!