【问题标题】:Loop that adds childs in Actionscript 3在 Actionscript 3 中添加子项的循环
【发布时间】:2012-04-02 14:18:54
【问题描述】:

我创建了一个包含书籍列表的 XML 文件, 现在阅读文件后,我想为列表中的每本书添加一个电影剪辑到舞台, 我知道如何添加一个孩子,但我想以不同的方式命名每个按钮,比如 book1_button、book2_button 等等, 我怎么做? 代码如下:

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++;
    }
}

【问题讨论】:

  • 你确实有一个 MovieClip 的 'name' 属性,对吧?

标签: xml arrays actionscript-3 actionscript


【解决方案1】:

我可以想到两种方法来解决这个问题:

1)。创建一个Array 并将所有书籍MovieClip 存储在该Array 中。如何做到这一点看起来像下面的代码:

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")

希望这会有所帮助!祝你好运。

【讨论】:

  • 我强烈建议第一种方法。
【解决方案2】:

您可以使用数组来存储书籍,然后您可以通过数组索引访问书籍(例如 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++;
    }
}

【讨论】:

    猜你喜欢
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    相关资源
    最近更新 更多