2010-02-25 47 views
1

我遇到一些問題,AS3字符串實例名稱動作腳本3

var eventChildren:XMLList = eventInput.channel.children(); 
var nr:Number; 
nr=0; 
for each (var eventInfo:XML in eventChildren) { 

    nr++; 
    trace(eventInfo.title); 
    var ev="ev"+String(nr); 
    var titl="title"+String(nr); 
    trace(ev); 
    trace(titl); 

    var newEV:Object = Object(ev); 
    var newTITL:Object = Object(titl); 

    trace(newEV); 
    trace(newTITL); 

    newEV.newTITL.text=eventInfo.title; 

} 

} 

這是我的代碼,我試圖設置標題值eventChild, ,因爲我每個子實例對於一般的動作腳本來說是新的,特別是動作腳本3我並不真正知道我在這裏做錯了什麼。我試圖從eventChildren中的值中爲ev1.title1,ev2.title2等設置文本,如下所示:first child,set ev1.title1,second ev2.title2等。關於我應該在代碼中更改什麼或想要查找某些信息的想法?

編輯:謝謝你的幫助,既解答了我正確的解決方案:

for each (var eventInfo:XML in eventChildren) { 

    nr++; 

    trace(eventInfo.title); 
    var ev="ev"+String(nr); 
    var titl="title"+String(nr); 
    //trace(ev); 
    //trace(titl); 

    var oTitle:Object = {}; // create object for the field titleXX 
    oTitle[titl] = {text:eventInfo.title}; // create and assign the field text to a new object 
    allFields[ev] = oTitle; // assign the title object to the field evXX 

} 

ev1.title1.text=allFields.ev1.title1.text; 
ev2.title2.text=allFields.ev2.title2.text; 
ev3.title3.text = allFields.ev3.title3.text; 
ev4.title4.text=allFields.ev4.title4.text; 

回答

2

EV和TITL被Strings而不是Object存在AS3沒有EVAL,所以你將不能夠要創建一個基於字符串名稱一個新的變量。但你可以創建一個新Object,將根據您的ev串有一個字段:

var o:Object={}; 
o[ev]="...."; 

所以,如果我的EV s等於字符串「ev1」,您將擁有一個名爲ev1的對象=> o.ev1 = ...

對於標題,您可以執行相同的操作,創建一個新的對象,該對象將具有基於TITL字符串:

var o:Object={}; 
o[titl]="..."; 

所以,如果TITL等於字符串「TITLE1」你將有一個名爲TITLE1 => o.title1 = ...

同樣的事情文本字段的對象,你必須創建一個Object來保存文本字段。

混合所有這些相關信息你結束了:

var eventChildren:XMLList = eventInput.channel.children(); 
var nr:Number=0; 
var AllFields:Object={}; 

for each (var eventInfo:XML in eventChildren) { 
    nr++; 
    trace(eventInfo.title); 
    var ev="ev"+String(nr); 
    var titl="title"+String(nr); 
    trace(ev); 
    trace(titl); 

    var oTitle:Object = {}; // create object for the field titleXX 
    oTitle[titl] = {text:eventInfo.title}; // create and assign the field text to a new object 
    allFields[ev] = oTitle; // assign the title object to the field evXX 
} 

// then you can have access to all your field within the object allFields 
trace(allFields.ev1.title1.text) 
trace(allFields.ev2.title2.text) 

參見本question爲對象符號

+0

謝謝你,這對我幫助很大 – Raz 2010-02-25 16:25:20

2

您可以使用 '這個' 變量名:

this['mystring'] = new Object(); 
this.mystring.title = 'mytitle'; 

如果你在一個班級裏面這樣做,班級必須是動態的,以允許新成員:

dynamic public class MyClass extends MovieClip { 
    public function MyClass() { 
     this['mystring'] = new Object(); 
     this.mystring.title = 'mytitle'; 
    } 
} 

如果你的類不是動態的,你仍然可以做到這一點,但必須繼續使用數組表示法,而不是點符號:

public class MyClass extends MovieClip { // not dynamic 
    public function MyClass() { 
     this['mystring'] = new Object(); 
     this['mystring'].title = 'mytitle'; 
    } 
}