【问题标题】:Titanium mobile get variable from event listener in loopTitanium移动从循环中的事件监听器获取变量
【发布时间】:2012-02-02 22:17:30
【问题描述】:

希望这是有道理的,我正在使用 Titanium mobile 构建 iPhone 应用程序。我有一个包含 100 个项目的数组,每个项目都有一个 DishID 和一个 DishTitle,我在 tableview 中显示 DishTitle,在事件侦听器上我需要传递 DishID 并在事件侦听器上使用警报我稍后会做一些事情项目 ID 这是我目前的代码:

var dishes = eval(this.responseText);

for (var i = 0; i < dishes.length; i++)
            {

                DishID[i] = dishes[i].DishID;

                var row = Ti.UI.createTableViewRow();
                    row.selectedBackgroundColor = '#fff';
                    row.height = 30;
                    row.className = 'datarow';
                    row.clickName = 'row';

                // Create the label to hold the screen name
                name[i] = Titanium.UI.createLabel({
                    color:'#000',
                    font:{fontSize:16,fontWeight:'bold', fontFamily:'Arial'},
                    left:5,
                    top:2,
                    height:30,
                    width:200,
                    text:dishes[i].DishTitle
                });

                name[i].addEventListener('click', function(e){

                                 alert(DishID[i]);
                            });

            }

我遇到的问题是,无论我点击哪个标签,我都会得到相同的 ID 208,我做错了什么吗?

【问题讨论】:

  • 我想知道“菜”是如何被初始化的。您是否验证过它们都是不同的 id?

标签: iphone titanium titanium-mobile


【解决方案1】:

您遇到了范围/关闭问题。当“点击”发生时,i=208。我发现最好将 eventListener 放在 table 上,并将自定义属性放在 row 上:

var table = Ti.UI.createTableView();
var rows = [];

for(var i = 0; i < dishes.length; i++) {

    var row = Ti.UI.createTableViewRow({
        selectedBackgroundColor : '#fff',
        height : 30,
        className : 'datarow'
    });

    row.dishId = dishes[i].DishID;

    // Create the label to hold the screen name
    var label = Ti.UI.createLabel({
        color : '#000',
        font : {
            fontSize : 16,
            fontWeight : 'bold',
            fontFamily : 'Arial'
        },
        left : 5,
        top : 2,
        height : 30,
        width : 200,
        text : dishes[i].DishTitle
    });

    row.add(label)

    rows.push(row);
}

table.setData(rows);

table.addEventListener('click', function(e) {
    alert(e.row.dishId);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多