【发布时间】:2016-03-01 06:10:46
【问题描述】:
我正在从 POST 查询我的网络服务中获取数据以构建动态菜单。我想要的是系统听到每个视图的点击事件,并识别它是什么。但是我不知道发生了什么,因为没有添加eventListener ...
我的代码如下:
getCategorias.onload = function() {
var json = this.responseText;
var response = JSON.parse(json);
for(var i = 0; i < response.length; i++) {
var containerAll = Ti.UI.createView({
width: "100%",
height: 130,
backgroundColor: "#000",
id: response[i].id
});
var viewImage = Ti.UI.createView({
backgroundImage: "http://www.iconomize.com.br/admin/"+response[i].foto,
backgroundColor: "#000",
opacity: "0.5",
width: "100%",
height: "100%",
top: "0"
});
var labelCat = Ti.UI.createLabel({
color: "#fff",
textAlign: "center",
width: "90%",
text: response[i].nome
});
containerAll.addEventListener('click', function(e){
alert(e.source.id);
});
containerAll.add(viewImage);
containerAll.add(labelCat);
$.listCategories.add(containerAll);
}
$.activityIndicator.hide();
};
【问题讨论】:
-
我认为更好的是,只需在
$.listCategories上添加一次侦听器,然后在侦听器函数中检查id,如$.listCategories.addEventListener('click', function(e){ alert(e.source.id); }); -
只是一个实用说明:将听众置于循环中并不是一个好主意。侦听器是被动的,不需要动态分配。我喜欢@Suraj 将它们添加到列表中的想法,然后在需要时调用它们。如果您需要删除它们,您可以遍历列表并迭代地应用
removeListener()。
标签: dom-events titanium addeventlistener titanium-mobile titanium-alloy