1.7节. 设置子节点属性<o:p></o:p>
<o:p></o:p>
1.7.1. 问题<o:p></o:p>
我想通过MXML中的script标签内容的某个方法来设置子节点属性。<o:p></o:p>
1.7.2. 解决办法<o:p></o:p>
通过id属性查找子节点组件,并使用id属性调用方法。<o:p></o:p>
1.7.3. 讨论<o:p></o:p>
人们很容易把组件的脚本代码部分与mxml部分分割开来看,但实际上它们是一体的,例如下面的例子:<o:p></o:p>
Code View:<o:p></o:p>
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300"> <o:p></o:p>
<mx:Script> <o:p></o:p>
<![CDATA[ <o:p></o:p>
private function changeAppearance():void <o:p></o:p>
{ <o:p></o:p>
this.width = Number(widthInputField.text); <o:p></o:p>
this.height = Number(heightInputField.text); <o:p></o:p>
} <o:p></o:p>
]]> <o:p></o:p>
</mx:Script> <o:p></o:p>
<mx:Image id="imageDisplay"/> <o:p></o:p>
<mx:Text text="Enter a width"/> <o:p></o:p>
<mx:TextInput id="widthInputField"/> <o:p></o:p>
<mx:Text text="Enter an height"/> <o:p></o:p>
<mx:TextInput id="heightInputField"/> <o:p></o:p>
<mx:Button click="changeAppearance()" label="Change Size"/> <o:p></o:p>
</mx:HBox> <o:p></o:p>
<o:p></o:p>
正如你所看到的,在changeAppearance方法中,this变量指向组件本身,即包含所有子节点组件的HBox,用于改变组件的宽度和高度。通过参照两个输入框widthInputField和heightInputField中的内容。每个输入框都是通过id属性进行引用,这跟在Document Object Model (DOM) 脚本中通过id引用是一样的。在整个程序中Id值必须是唯一的,可用于指向单级层次结构内部一个组件而不管组件之间的嵌套关系:<o:p></o:p>
Code View:<o:p></o:p>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" width="520" height="650"> <o:p></o:p>
<mx:Script> <o:p></o:p>
<![CDATA[ <o:p></o:p>
private var fileName:String = ""; <o:p></o:p>
private function saveResume():void <o:p></o:p>
{ <o:p></o:p>
//....a service call to send the data and set the filename <o:p></o:p>
fileNameDisplay.text = "Your resume has been saved as "+fileName; <o:p></o:p>
} <o:p></o:p>
]]> <o:p></o:p>
</mx:Script> <o:p></o:p>
<mx:Text id="fileNameDisplay" text="" width="500"/> <o:p></o:p>
<mx:RichTextEditor id="richTextControl" width="500" height="400"/> <o:p></o:p>
<mx:Button id="labelButton" label="Submit Resume" click="saveResume()"/> <o:p></o:p>
</mx:VBox> <o:p></o:p>
<o:p></o:p>
上面的例子中,通过id属性来引用子节点组件并通过id设置其属性值,MXML中的所有添加进来的组件默认下都是可视的,父组件都可以访问到它们。<o:p></o:p>
<o:p>
</o:p>