问题描述
有没有更好的(更快,更短或整洁)的方式来访问3层或更深的儿童精灵(对象)?如果孩子们都被给了名字,而且你知道名字。有没有更好的办法做到这一点比我下面的代码?var mySprite:DisplayObjectContainer = layerASprite.getChildByName( layerA )作为DisplayObjectContainer;
mySprite = mySprite.getChildByName( layerB )作为DisplayObjectContainer;
mySprite.getChildByName( layerC )。y = 200;
是独一无二的,你可以创建一个静态类变量/方法的形式全球注册表:
包
{
public class Registry
{
static private var hash:Object = new Object;
static public function register(name:String,target:DisplayObject):void
{
hash [name] = target;
static public function access(name:String):DisplayObject
{
return hash [name];
$ b用法: //任何MovieClip,第1帧或类构造函数。
导入注册表;
Registry.register(deepChild,this);
//从任何其他地方。
导入注册表;
Registry.access(deepChild)。y = 200;
或者,您可以使用一种方法,通过单个字符串参数来挖掘子元素的子元素:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ );
var result:DisplayObject = this;
while(aSplit.length)
{
var aParent:DisplayObjectContainer = result作为DisplayObjectContainer;
if(!aParent)return null;
result = aParent.getChildByName(aSplit.shift());
}
返回结果;
$ / code $ / pre
用法:
offSpring(layerA.layerB.layerC)。y = 200;
Is there a better (quicker, shorter or neater) way to access a child sprite (object) 3 layers or more deep? If the children have all been given names and you know the names. Is there a better way to do it than the code I made below?
var mySprite:DisplayObjectContainer = layerASprite.getChildByName("layerA") as DisplayObjectContainer;
mySprite = mySprite.getChildByName("layerB") as DisplayObjectContainer;
mySprite.getChildByName("layerC").y = 200;
解决方案 If they are unique you can create a "global" registry in a form of static class variables/methods:
package
{
public class Registry
{
static private var hash:Object = new Object;
static public function register(name:String, target:DisplayObject):void
{
hash[name] = target;
}
static public function access(name:String):DisplayObject
{
return hash[name];
}
}
}
Usage:
// Any MovieClip, frame 1 or class constructor.
import Registry;
Registry.register("deepChild", this);
// From any other place.
import Registry;
Registry.access("deepChild").y = 200;
Alternately you can use a method that digs children of children by a single string argument:
function offSpring(path:String):DisplayObject
{
var aSplit:Array = path.split(".");
var result:DisplayObject = this;
while (aSplit.length)
{
var aParent:DisplayObjectContainer = result as DisplayObjectContainer;
if (!aParent) return null;
result = aParent.getChildByName(aSplit.shift());
}
return result;
}
Usage:
offSpring("layerA.layerB.layerC").y = 200;
这篇关于AS3:如何访问儿童的孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!