Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用钛合金Appcelerator中的循环创建元素和addEventListener_Javascript_Titanium_Titanium Mobile - Fatal编程技术网

Javascript 使用钛合金Appcelerator中的循环创建元素和addEventListener

Javascript 使用钛合金Appcelerator中的循环创建元素和addEventListener,javascript,titanium,titanium-mobile,Javascript,Titanium,Titanium Mobile,使用Tianium 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,

使用Tianium 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
    }
}
有趣的是,它找不到的变量不是“testLabels1”,这对我来说意味着循环没有触发。。。有什么想法吗

谢谢

钛合金不喜欢我在标签声明前加上“var”。

试试这个

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

}
var testLabels=[];
对于(var i=0;i试试这个

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

}
var testLabels=[];

for(var i=0;感谢您的帮助!!答案是将testLabels定义为数组。我简直不敢相信我没有看到。您答案的第二部分,添加事件侦听器,对我来说不起作用。我最终使它这样工作:theLabel=testLabels[i];win2.add(theLabel);theLabel.addEventListener('click',function(){})谢谢你的帮助!!答案是将testLabels定义为数组。我不敢相信我没有看到。你的答案的第二部分,添加事件侦听器,对我来说不起作用。我最终使它这样工作:theLabel=testLabels[I];win2.add(theLabel);theLabel.addEventListener('click',function(){})