【问题标题】:Sqlite jquery nested loopSqlite jquery 嵌套循环
【发布时间】:2013-06-14 18:51:16
【问题描述】:

我在这方面有点新手 - 我已经尝试了几天来修改各种 stackoverflow 答案,但没有任何运气。

对于我的 phonegap 应用程序 - 使用 sqlite、jquery 我试图遍历一个类别表,然后为每个类别创建一个嵌套的“种类”列表。下面的代码产生外循环,但不产生内循环。

任何帮助将不胜感激

db.transaction(function (tx) {
     tx.executeSql('SELECT * FROM cat;', [], function (transaction, catResult) {
          var theHtml ='';
          for (var i = 0; i < catResult.rows.length; i++) {
               // outer loop
                var catRow =catResult.rows.item(i);
               theHtml +='<li>' +catRow.Name;
               function doinner(i) {
                    var theHtml2 ='';
                    tx.executeSql('SELECT * FROM kind WHERE cat_id = ?;', [catRow.Id], function (transaction, kindResult) {
                         theHtml2 ='<ul>';
                         for (var i2 = 0; i2 < kindResult.rows.length; i2++) {
                              // inner loop
                               var kindRow =kindResult.rows.item(i2);
                              theHtml2 +='<li>' +kindRow.kind +'</li>';
                         };
                         // end inner loop
                          theHtml2 +='</ul>';
                    });
                    // end function
                     theHtml +=theHtml2;
               }
               // end doinner
               doinner(i) ;
                // this function is supposed to assemble and append the inner loop
                theHtml +='</li>';
          }
          // end outer loop
           $('#catList').html(theHtml);
     });
     // end function

});
 // end transaction

【问题讨论】:

    标签: jquery html sqlite loops cordova


    【解决方案1】:

    你给executeSql的回调函数是异步执行的,所以theHtml2在你使用的时候还不包含任何东西。

    处理此问题的更简单方法是使用带有连接的单个查询获取数据,然后使用单个循环来构造 HTML 列表:

    tx.executeSql('SELECT cat.name, kind.kind ' +
                  'FROM cat ' +
                  'LEFT JOIN kind ON cat.id = kind.cat_id '+
                  'ORDER BY 1, 2',
                  [], function(tx, result) {
        var theHtml = '';
        var lastName = '';
        for (var i = 0; i < result.rows.length; i++) {
            var row = result.rows.items(i);
            if (row.name != lastName) {
                if (theHtml != '')
                    theHtml += '</ul>';
                theHtml += '<li>' + row.name;
                lastName = row.name;
                theHtml += '<ul>';
            }
            if (!!row.kind)
                theHtml += '<li>' + row.kind + '</li>';
        }
        if (theHtml != '')
            theHtml += '</ul>';
        $('#catList').html(theHtml);
    });
    

    【讨论】:

    • 哦,谢谢,我对此有点陌生,你能告诉我如何将 html 创建为嵌套列表
    猜你喜欢
    • 1970-01-01
    • 2020-01-03
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 2022-01-14
    相关资源
    最近更新 更多