Javascript 使用钛合金Appcelerator中的循环创建元素和addEventListener
使用Tianium Appcelerator,我尝试动态创建元素,并使用循环向元素添加事件侦听器。这是我目前的代码: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,
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(){})