2013-12-17 29 views
0

如何引用在運行時添加的子元素?Actionscript對子元素的引用

示例代碼:

for(var i:Number=1; i<=5;i++){ 
    var mygroup:HGroup = new HGroup(); 

    var mybutton:Button = new Button(); 
    mybutton.label = "Browse Directory"; 
    mybutton.addEventListener(MouseEvent.CLICK,browsedirectory); 

    var dirlbl:Label = new Label(); 
    dirlbl.text = "C:/some directory/"; 
    dirlbl.id = "path"+i; 

    mygroup.addElement(mybutton); 
    mygroup.addElement(dirlbl); 
    mygroup.id = "group"+i; 
    mainGroup.addElement(mygroup); 
} 

public function updatepath():void 
{ 
    this["path1"].text = "new path"; 
} 

當我試圖通過調用this["path1"].text = "new path";更改標籤的目錄路徑,並運行到錯誤

Error #1069: Property path1 not found and there is no default value. 

我怎麼可以參考這些子元素?

謝謝。

+0

「this」在您的代碼中是指什麼? –

+0

'這'來自根。 – user1995781

+0

檢查這些鏈接[link1](http://www.daveoncode.com/2009/05/20/objectcollector-accessing-dynamic-generated-flex-objects-by-id/)[link2](http:// www .jumpingbean.co.za/blogs/mark/flex_reference_components_dynamic_runtime_creation) –

回答

1
Caution, code not tested! 

你可以首先檢查在特定容器中的所有元素(你自己的知識):

private function displayChildren(element):void { 
    for (var i = 0; i < element.numChildren; i++){ 
     var child = element.getChildAt(i); 

     if (child != null) { 
      trace ('position: '+i+' child name:' + child.name); 

      for (var j = 0; j < child.numChildren; j++){ 
       displayChildren(child.getChildAt(j)); 
      } 
     } 
    } 
} 

displayChildren(mainGroup); 

這應該輸出類似:

trace= position: 0 child name : "group1";  <- HGroup 
trace= position: 0 child name : undefined; <- Button without id 
trace= position: 1 child name : "path1";  <- Label 
... 

所以在這之後,你應能夠以下列方式訪問標籤:

mainGroup["group1"]["path1"].text = "new path text"; 

--------------------更新-------------------------- -

如果您執行以下操作,會發生什麼情況?

var vgroup = mainGroup.getChildByName("group1"); 
if (vgroup != null) { 
    trace(vgroup.id) 
    var label = vgroup.getChildByName("path1"); 
    if (label != null) { 
     trace(label.id) 
     label.text = "change label text" 
    } 
} 

您是否獲得輸出?

+0

感謝您的回答。所有元素都在容器中。但是當我用你的例子引用它時,它仍然會拋出錯誤:錯誤#1069:在spark.components.VGroup上找不到屬性組1,並且沒有默認值。「 – user1995781

+0

查看更新的答案。 –

+0

@ user1995781 - 如果解決方案正常工作 - 請接受答案或讓我知道是否需要更多信息。 –