钛 - 循环和视图的内容问题

Titanium - Content Issue with Loops and Views

本文关键字:问题 视图 循环      更新时间:2023-09-26


嗨,我是 Titanium 的新手,在我的项目中,我正在循环一些 JSON 数据,这些数据为我的应用程序页面标题和内容提供服务。我有这个功能:

xhr.onload = function() {
    try {
    var myPages = JSON.parse(this.responseText);
    for (var c=0;c<myPages.length;c++){ 
      var title = myPages[c].title; // page title
      var content = myPages[c].content; // page content

我已将页面标题作为标签添加到 TableViewRow 中:

      var row = Ti.UI.createTableViewRow({hasChild:true,height:Ti.UI.SIZE,backgroundColor:bgcolor});
      // Create a vertical layout view to hold all the titles
      var post_view = Ti.UI.createView({
          height: Ti.UI.SIZE,
          layout:'vertical',
          left:5,
          etc..
      });          
      // Create article titles
      var label_title = Ti.UI.createLabel({
          text:title,
          left:5,
          etc...
      });
    // Add the article titles to the view
    post_view.add(label_title);
    // Add the vertical layout view to the row
    row.add(post_view);
    row.className = 'item'+c;
    data[c] = row;

这一切都工作正常,我得到一个表格,每行都有我的页面标题,但是当用户单击标题时,我希望应用程序打开一个新的视图/窗口以显示相应页面的内容。这就是我的麻烦开始的地方!

我添加了这个函数来尝试处理这种情况:

    // Add an event listener to the rows
    row.addEventListener('click', function(){
        Titanium.API.info('row has been clicked');
        // Create view for article content
        var articleView = Titanium.UI.createView({
            height: Ti.UI.SIZE,
            layout:'vertical',
            left:5,
            etc..
        });
        var t = Ti.UI.iPhone.AnimationStyle.FLIP_FROM_LEFT;
        win.animate({view:articleView,transition:t});
        var articleViewContent = Ti.UI.createLabel({
            text:content,
            left:5,
            etc..
        });
        // Add the content to the view
        articleView.add(articleViewContent);
     });
     }
    // Create the tableView and add it to the window.
    var tableview = Titanium.UI.createTableView({data:data,minRowHeight:58});
    win.add(tableview);
    }
    catch(E){
        alert(E);
    }
};

我可以得到对标题单击输入的响应以显示在控制台中,但我无法弄清楚如何在新视图中调用相应的内容。我认为计数器应该存储它(从创建标题时开始(,但不知道如何访问它。

我有点迷茫,觉得我可能会搞砸这里的一些基本面。我对 JavaScript 也比较陌生,所以请原谅任何错误!如果能得到一些建议来帮助我改进,那就太好了!
(我在代码中添加了一些"等"以缩短内容(

首先向行本身添加某种content属性,以便以后通过行单击事件访问它。按如下方式调整行定义:

var row = Ti.UI.createTableViewRow({
    content: content,  // contains the article content from myPages[c].content
    hasChild:true,
    height:Ti.UI.SIZE,
    backgroundColor:bgcolor
});

然后,您需要将事件传递给该行的事件侦听器中的回调函数:

row.addEventListener('click', function(ev){
    Titanium.API.info('row has been clicked:'+JSON.stringify(ev)); // this will allow you to see the event's properties
    ...
    // you can access the content attribute of the row by using ev.row.content
    var articleViewContent = Ti.UI.createLabel({
        text:ev.row.content,
        left:5,
        etc..
    });
}