cari

Rumah  >  Soal Jawab  >  teks badan

javascript - artTemplate 如何遍历这样的数据



<p id="content"></p> <script id="test" type="text/html"> <h1>{{title}}</h1> <ul> {{each data as value i}} <li>索引 {{i + 1}} :{{value}}</li> {{/each}} </ul> </script> <script> var data = [{ title: '基本例子1', data: ['文艺1', '博客1', '摄影1', '电影1', '民谣1', '旅行1', '吉他1'] },{ title: '基本例子2', data: ['文艺2', '博客2', '摄影2', '电影2', '民谣2', '旅行2', '吉他2'] }]; for (d in data) { // alert(JSON.stringify(data[d])) var html = template('test', data[d]); } document.getElementById('content').innerHTML = html; </script>

这样子遍历为什么只出来1组?

PHPzPHPz2895 hari yang lalu471

membalas semua(4)saya akan balas

  • PHPz

    PHPz2017-04-10 15:33:45

    可能你理解有误

    应该是

    var data = {
        list : [{
            title : 'xxx1',
            tags : ['文艺1', '博客1', '摄影1', '电影1']
        },
        {
            title : 'xxx2',
            tags : ['文艺2', '博客2', '摄影2', '电影2']
        }]
    }
    var html = template('test', data)
    document.getElementById('content').innerHTML = html;
    

    然后模板部分可以这么写

    <script id="test" type="text/html">
    {{if isAdmin}}
    {{each list as item i}}
    <h1>{{item.title}}</h1>
    <ul>
        {{each item.tags as tag i}}
            <li>索引 {{i + 1}} :{{tag}}</li>
        {{/each}}
    </ul>
    {{/each}}
    {{/if}}
    </script>
    

    bug fix

    for (d in data) {
    //  alert(JSON.stringify(data[d]))
    var html = template('test', data[d]);
    }
    document.getElementById('content').innerHTML = html;
    
    

    你说的 只出来一组是因为 你一个for in 后,
    html 代表的是最后一组数据的html 呢。

    balas
    0
  • PHPz

    PHPz2017-04-10 15:33:45

    请问JS如何操作artTemplate编译过的元素呢?

    balas
    0
  • 高洛峰

    高洛峰2017-04-10 15:33:45

    var html ='';
    for (i in data) {
        //  alert(JSON.stringify(data[d]))
        var html = template('test', data[i])+html;
        console.log(i);
    }

    html要累加 你原来的会覆盖

    balas
    0
  • PHPz

    PHPz2017-04-10 15:33:45

    你这个使用item的时候不加#引用,不会报错的吗?

    balas
    0
  • Batalbalas