如何在Javascript中调用动态命名的方法? [英] How do I call a dynamically-named method in Javascript?

查看:141
本文介绍了如何在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将用于根据另一个列表框中的选择填充列表框。当选择一个列表框时,它将根据列表框的选定值调用方法名称。

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包含:

Listbox1 contains:

颜色

形状

Colours
Shapes

如果'选择颜色'然后它将调用填充另一个列表框的populate_Colours方法。

澄清我的问题:如何在Javascript中进行populate_Colours调用?

If 'Colours' is selected then it will call a "populate_Colours" method that populates another listbox.
To clarify my question: how do I make that "populate_Colours" call in Javascript?

推荐答案

假设'populate_Colours'方法在全局命名空间中,您可以使用以下代码,这两个代码都利用了可以访问所有对象属性的方法,就像对象一样是一个关联数组,并且所有全局对象实际上都是窗口主机对象的属性。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆