简体   繁体   English

在Titanium Appcelerator中使用Loop创建元素和addEventListener

[英]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. 使用Titanium Appcelerator,我试图动态创建元素,并使用循环向其添加事件侦听器。 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? 对我来说有趣的是,它找不到的变量不是“ testLabels1”,这对我来说意味着循环没有触发……任何想法?

Thanks! 谢谢!

Titanium doesn't like it when I place "var" in front of the label declaration. 当我在标签声明的前面放置“ var”时,Titanium不喜欢它。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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