2012-04-02 47 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++; 
    } 
}