我对我在下面这段代码中看到的内容感到困惑。我有一个带有子按钮(我已指定其名称)的盒子容器。我编写了一个函数,试图按名称查找子按钮。但是,这并没有按预期工作 - 盒子的原因是 numChildren=0 出于某种原因,我希望它是 1,因为我在小时候添加了一个按钮。有人可以帮我理解我做错了什么吗?
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<mx:Box height="100%" width="100%" initialize="initializeApp();" name="MyBox">
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.controls.Button;
import mx.core.FlexGlobals;
public function initializeApp():void {
var btn:Button = new Button();
btn.name = "MyButton";
addElement(btn);
btn.addEventListener(MouseEvent.CLICK, clickCallback);
}
private function clickCallback(event:MouseEvent):void{
var obj:DisplayObject = findChildByName(FlexGlobals.topLevelApplication as DisplayObjectContainer, "MyButton");
if (obj==null){
Alert.show( "Not Found");
}
else{
Alert.show( "Found");
}
}
private function findChildByName(parent:DisplayObjectContainer, name:String):DisplayObject{
var childCount:Number = (parent==null) ? 0 : parent.numChildren;
for (var i:Number=0;i<childCount;i++){
var child:DisplayObject = parent.getChildAt(i);
if (child is DisplayObjectContainer){
return findChildByName(child as DisplayObjectContainer, name);
}
else{
if (parent!=null && child == parent.getChildByName(name)){
return child;
}
}
}
return null;
}
]]>
</fx:Script>
</mx:Box>
</s:WindowedApplication>
谢谢你。