I'm moving from cocos2d-html5 version 2.2 to cocos2d-js 3.0 and I have a problem with this code (which works perfectly in version 2.2):

        menuButtons = cc.Menu.create();
        for (var a = 1; a < 6; a++){

            var label = cc.LabelTTF.create("BUTTON " + a, "Arial", 20);
            var tmpBtn = cc.MenuItemLabel.create(label, function (e) {
                cc.log("TEST TAG: " + e.tag);
                //StartSomethingOther(e);
            }, this);

            tmpBtn.setPosition(50, a * 30);
            tmpBtn.tag = a;

            menuButtons.addChild(tmpBtn,2,1);

        }
        menuButtons.setPosition(10, 10);
        this.addChild(menuButtons, 1);

Any "button" is pressed the console always output "TEST TAG: 1" instead of putting the correct number. Any tip to solve the problem?

有帮助吗?

解决方案

Change the .tag with .title or even better a ['data-'] identifier like in this example:

        menuButtons = cc.Menu.create();
        for (var a = 1; a < 6; a++){

            var label = cc.LabelTTF.create("BUTTON " + a, "Arial", 20);
            var tmpBtn = cc.MenuItemLabel.create(label, function (e) {
                cc.log("TEST TAG: " + e['data-tag']);
                //StartSomethingOther(e);
            }, this);

            tmpBtn.setPosition(50, a * 30);
            tmpBtn['data-tag'] = a;

            menuButtons.addChild(tmpBtn,2,1);

        }
        menuButtons.setPosition(10, 10);
        this.addChild(menuButtons, 1);          

其他提示

You're overwriting tag property here:

menuButtons.addChild(tmpBtn,2,1);

the third parameter sets tmpBtn.tag to 1.

If You want to continue to use tag property simply change:

        tmpBtn.tag = a;
        menuButtons.addChild(tmpBtn,2,1);

with:

        menuButtons.addChild(tmpBtn,2,a);

If You don't want to use tag property, see Francesco's answer

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top