简体   繁体   中英

Create elements and addEventListener with Loop in Titanium Appcelerator

Using Titanium Appcelerator I am trying to dynamically create elements and add event listeners to them using a loop. Here is my current code:

for(i=0;i<7;i++){

testLabels[i] = Titanium.UI.createLabel({
    borderRadius: 35,
    text:'hello',
    textAlign:'center',
    width:70,
    height: 70,
    top: '13%',
    left:140,
    touchEnabled: true
});

    testLabels[i].addEventListener('click',function(e){
        //do something
    }
}

When I run this I get the following error:

Can't find variable: testLabels. 

Its interesting to me that the variable it can't find isn't "testLabels1", which to me means the loop isn't firing... any ideas?

Thanks!

Titanium doesn't like it when I place "var" in front of the label declaration.

try this

var testLabels = [];
for(var i=0; i<7; i++ ) {

    testLabels[i] = Titanium.UI.createLabel({
        borderRadius: 35,
        text:'hello',
        textAlign:'center',
        width:70,
        height: 70,
        top: '13%',
        left:140,
        touchEnabled: true
    });

    (function(label) {
        label.addEventListener('click',function(e){
            //do something
        }
    }(testLabels[i]));

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM