0

使用 Titanium Appcelerator 我正在尝试动态创建元素并使用循环向它们添加事件侦听器。这是我当前的代码:

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

当我运行它时,我收到以下错误:

Can't find variable: testLabels. 

有趣的是,它找不到的变量不是“testLabels1”,这对我来说意味着循环没有触发......有什么想法吗?

谢谢!

当我在标签声明前面放置“var”时,Titanium 不喜欢它。

4

1 回答 1

4

试试这个

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]));

}
于 2011-11-15T09:50:46.180 回答