我有一個組用戶控件,並且在控件內部定義了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'變量。 –