Access dynamic text field within a button using an event handler
I have what seems to be a simple task, yet I cannot seem to figure it out. I am busy creating a project in ActionScript 3, and while I am fairly fluent in ActionScript 2, I am being stumped a 开发者_JAVA百科bit here.
I have a simple dynamic text field inside a button object. This text field has the name of txt_title. I have attached event handlers to change the alpha of the buttons when they are hovered over, however I also want to change the value of the text field within the button, when hovered over. My event listener looks like follows:
function hoverHandler(Event:MouseEvent):void{
var object:Object = Event.target;
var txt:TextField = object.txt_title;
txt.text = "TEST";
object.alpha = 1;
}
The alpha works fine, however I keep getting the following error while trying to manipulate the text field:
ReferenceError: Error #1069: Property txt_title not found on flash.display.SimpleButton and there is no default value. at main_fla::MainTimeline/hoverHandler()
Any light shed on this issue will be much appreciated,
Simon
Event is a class name, change it to a lower case to make sure you're not having a namespace issue.
In addition, make sure you're working with the right object. I've added a trace statement to see what the toString method has to say. When you know what object type it is, you should cast it as such so you can see what properties it has at compilation and not during runtime. ( I've named it simple button because that's what the error says. )
function hoverHandler(event:MouseEvent):void{
trace(event.target);
var object:SimpleButton = event.target as SimpleButton;
var txt:TextField = object.txt_title;
txt.text = "TEST";
object.alpha = 1;
}
All the above considered, this code will still not work. You have attached the event listener to a SimpleButton object. I wasn't that great in as2, but it seems like you're programming in a python or javascript mentality. Adding the property to the object at runtime will not work.
Another method to obtain the textfield is to look in the DisplayContainer. You can do this like so:
for(var i:uint = 0; i < sb.numChildren ; i++)
{
trace(sb.getChildAt(i));
}
Once you found the TextField in the DisplayContainer, you then can perform the operations that you want to perform.
It may be, that event.target returns the DisplayObject within your object that is firing the event.
There are two methods to prevent this from happening:
inside the button declare:
mouseChildren = false;
or in the EventListener reference the object with currentTarget:
var object : SimpleButton = event.currentTarget as SimpleButton;
It may also be, that your txt_title TextField is not public, but private.
Also the textField has to be in the base of the SimpleButton. It will not work if it is nested further in another container Object.
精彩评论