我有一个组用户控件,并且在控件内部定义了javascript。在一个页面中,我有两个独立工作的控件。渲染JavaScript是类似下面的东西:访问具有相同名称的javascript对象
//control 1
var Groups = (function() {
var obj = {};
obj.selectedid = 2;
return obj;
}());
//control 2
var Groups = (function() {
var obj = {};
obj.selectedid = 2; //it is different here, to keep it simple i just hardcoded as '2'
return obj;
}());
谁能告诉我如何在页面上访问1组变量(控制)。我认为像组[0]会给我的结果,但事实并非如此。
感谢您的回复。非常感激。我正在添加更多信息以便清楚。用户控件包含双列表框,用户可以添加/删除从列表1到列表2的值。所以我已经封装了所有这些逻辑如下。
var Groups = (function() {
var obj = {};
obj.selectedid = 2;
//some local functions for internal operations such as
function moveGroups(source, target){
}
//there are public functions to initialize this control or to add groups as below
// Groups can be added from external page by calling Groups.AddGroups(data);
obj.AddGroups = function(data) {
//refers to local variables and functions and adds data to listboxes
};
return obj;
}());
问题是我在页面上有两个这样的组控件。组1包含它自己的双重列表并且类似于组2。现在,我需要访问两个对象的AddGroups函数,这两个对象独立工作,如从页面的Groups1.AddGroups(data)或Groups2.AddGroups(data)。
我已经用下面的解决方案制定出来了。
在我的网页var Groups = Groups || []; //Check object already exists
Groups.push(
//kept all the existing code here...
(function() {
var obj = {};
obj.selectedid = 2;
//some local functions for internal operations such as
function moveGroups(source, target){
}
//there are public functions to initialize this control or to add groups as below
// Groups can be added from external page by calling Groups.AddGroups(data);
obj.AddGroups = function(data) {
//refers to local variables and functions and adds data to listboxes
};
return obj;
}())
);
现在,我是指使用:
Groups[0].AddAvailGroups();
Groups[1].AddAvailGroups();
你的第二个'Groups'变量覆盖你的第一个'Groups'变量。 –