欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

flex之下拉框值更改事件调用JavaScript函数

程序员文章站 2022-05-05 21:28:26
...
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   initialize="initApp()"
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
	<s:layout>
		<s:BasicLayout/>
	</s:layout>

	<fx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;
			import mx.controls.Alert;
			
			import spark.events.IndexChangeEvent;  
			
			[Bindable]  
			private var datas:ArrayCollection = new ArrayCollection([{label:"选项1"},{label:"选项2"},{label:"选项3"},{label:"选项4"}]);  
			
			//第一步:在mxml应用程序启动后执行:把js可以调用的ActionScript 函数注册
			public function initApp():void 
			{   
				//把flexHelloWorld 函数注册成名为flexHelloWorld,可以供js调用
				ExternalInterface.addCallback("flexHelloWorld", flexHelloWorld);   
			}
			
			//供js调用的ActionScript函数,这里的param1,param2是从js传递回来的参数
			public function flexHelloWorld(param1:String, param2:String):void 
			{   
				Alert.show("param1: " + param1 + "; param2:" + param2);   
			}  
			
			protected function userName_changeHandler(event:TextOperationEvent):void
			{
				//flex调用JavaScript函数的方式:如下:第一个参数是JavaScript中的函数名称,第二个参数
				//是JavaScript函数中接受的参数
				ExternalInterface.call("javascriptFunction",userName.text);
			}
			
			protected function newItem_clickHandler(event:MouseEvent):void
			{
				var s:String = itemValue.text;
				datas.addItem(s);
				items.selectedIndex = datas.length;
				itemValue.text="";
			}
			
			protected function delItem_clickHandler(event:MouseEvent):void
			{
				datas.removeItemAt(items.selectedIndex);
				items.selectedIndex=0;
			}

			//下拉框值更改事件
			protected function items_changeHandler(event:IndexChangeEvent):void
			{
				//调用JavaScript中的函数
				ExternalInterface.call("javascriptFunction",userName.text);
				Alert.show(event.currentTarget.toString());
			}

		]]>
	</fx:Script>

	<fx:Script>
		<![CDATA[
			import spark.events.TextOperationEvent;
		]]>
	</fx:Script>
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
	</fx:Declarations>
	
	<s:TextInput id="userName" change="userName_changeHandler(event)" />
	<s:Panel width="250" height="200" title="下拉框案例" x="0" y="60">
		<s:TextInput id="itemValue" x="10" y="75" width="150"/>
		<s:Button id="newItem" x="168" y="75" label="新建项" click="newItem_clickHandler(event)"/>
		<s:ComboBox id="items" x="10" y="34" width="228" dataProvider="{datas}" selectedIndex="0" change="items_changeHandler(event)"/>
		<s:Button id="delItem" x="168" y="104" label="删除选中" click="delItem_clickHandler(event)"/>
	</s:Panel>
</s:Application>