如何引用在运行时添加的子元素?
示例代码:
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 :(得分: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"
}
}
你得到了输出吗?