Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Actionscript 3 AS3:如何在MouseEvent侦听器中使用带变量的函数?_Actionscript 3_Mouseevent - Fatal编程技术网

Actionscript 3 AS3:如何在MouseEvent侦听器中使用带变量的函数?

Actionscript 3 AS3:如何在MouseEvent侦听器中使用带变量的函数?,actionscript-3,mouseevent,Actionscript 3,Mouseevent,通常使用鼠标事件侦听器,如下所示: MyButton.addEventListener(MouseEvent.MOUSE_UP, MyFunction); function MyFunction(event:MouseEvent):void { // my function codes //... //... } 但我想在函数中使用一个变量,类似这样: //var Tx:Number = any Formula; MyButton.addEventListener(MouseEvent.M

通常使用鼠标事件侦听器,如下所示:

MyButton.addEventListener(MouseEvent.MOUSE_UP, MyFunction);
function MyFunction(event:MouseEvent):void
{
// my function codes
//...
//...
}
但我想在函数中使用一个变量,类似这样:

 //var Tx:Number = any Formula;
 MyButton.addEventListener(MouseEvent.MOUSE_UP, MyFunction(Tx));
 function MyFunction(event:MouseEvent,T:Number):void
 {
    if ( T == 1 ) { ... }
    if ( T == 2 ) { ... }
    if ( T == 3 ) { ... }
 }

我该怎么做呢?

我想你会把监听器连接到不同的按钮/电影唇上。然后,访问event.currentTarget并更改变量的值

button1.addEventListener(MouseEvent.MOUSE_UP, doSomething);
button2.addEventListener(MouseEvent.MOUSE_UP, doSomething);
function doSomething(event:MouseEvent):void {
var str:String;
if (event.currentTarget.name == 'button1')
str = 'one';
else
str = 'two';
}

或者类似的东西。

在我看来,你似乎想要创建一个闭包

function process(t:Number)
{
    return function(event:MouseEvent) {
        if ( t == 1 ) { ... }
        if ( t == 2 ) { ... }
        if ( t == 3 ) { ... }
    }
}

MyButton.addEventListener(MouseEvent.MOUSE_UP, process(1));
这将从“进程”返回一个函数,该函数将作为事件侦听器的一个函数,并包含参数T


ps:即使ActionScript允许提升函数(即在定义之前调用的函数),我也认为这是一种糟糕的风格。也可以使用小写作为参数名。大写名称通常表示这是一种类型。

完全正确!我希望将侦听器附加到不同的按钮,然后按每个按钮执行操作。感谢@joeThanks@robkuz为您编辑和回答。我被你的as3代码弄糊涂了!我将尝试你的代码,并在这里说结果…参数“t”没有进入函数!我在函数中跟踪了“t”,但没有在输出面板中写入任何内容。您是否尝试访问
process
函数定义之外的
t
?那是行不通的。在定义闭包的外部,闭包参数不可见。