2012-04-02 62 views
2

我创建了一个XML文件,其中包含一本书的列表, 现在阅读文件后,我想为列表中的每本书添加一个动画片段, 知道如何添加一个孩子,但我想为每个按钮命名不同,比如book1_button,book2_button等等, 我该怎么做? 继承人的代码:在Actionscript 3中添加子元素的循环3

function createChilds():void{ 
    var i:Number = 1; 
    //For loop that iterates through all of the books in the XML file 
    for each (var bookID:XML in booksList) { 

     var bookButton:MovieClip = new book_btn; 
     this.addChild(bookButton); 

     i++; 
    } 
} 
+0

您确实拥有MovieClip的'name'属性,对吧? – Subodh 2012-04-02 14:28:37

回答

3

有两种方法,我能想到的解决这个问题:

1)。创建一个Array,并在Array中存储所有的书MovieClip。怎么会做看起来像下面的代码:

var bookArray:Array = []; 
function createChilds():void{ 

    //For loop that iterates through all of the books in the XML file 
    for each (var bookID:XML in booksList) { 

     var bookButton:MovieClip = new book_btn; 
     this.addChild(bookButton); 
     bookArray.push(bookButton); // Add to the array 
    } 
} 

然后访问一本书,你只想用bookArray[1]bookArray[2]等等...

2)。为每本书命名一些不同的东西,并使用getChildByName("name")。这个问题是,如果你意外地搞砸了,并有两个同名,你会遇到一些麻烦。但这里是它如何工作的:

function createChilds():void{ 
    var i:Number = 1; 
    //For loop that iterates through all of the books in the XML file 
    for each (var bookID:XML in booksList) { 

     var bookButton:MovieClip = new book_btn; 
     this.addChild(bookButton); 
     bookButton.name = "book"+i.toString();  // Name the book based on i 
     i++;       
    } 
} 

然后访问每本书你会使用getChildByName("book1")

希望这有助于!祝你好运。

+1

我会强烈建议第一种方法。 – jhocking 2012-04-02 14:30:38

0

您可以使用数组来存储书籍,然后通过数组索引(例如bookArray [3])访问书籍。

var bookArray:Array = []; 

function createChilds():void{ 
    var i:Number = 1; 
    //For loop that iterates through all of the books in the XML file 
    for each (var bookID:XML in booksList) { 
     var bookButton:MovieClip = new book_btn; 
     this.addChild(bookButton); 
     bookArray.push(bookButton); 
     i++; 
    } 
}