列表加载显示(网页)

网页中的列表加载一般不会用标签追加的方式去实现,很容易因为标点符号等问题出错。博主虽然为初学者,但是也坚决不要踩这个坑!!!哈哈。。。也要学会使用模板来实现。网上百度了一个轻量级的模板:doT.min.js。使用起来也很简单粗暴!
先写好列表其中一项的布局样式即可,也就是Android中所谓的的item样式。
1、实现要引入这个js

<script type="text/javascript" src="../script/doT.min.js"></script>
<body>
    <div id="content"></div>
</body>

2、写样式,注意:外层是script标签包含。其实这属于一个执行的方法,只不过是把写好的样式移到这里面而已。

<script type="text/x-dot-template" id="temp">
    {{~it:bean:index}}
    <div class="item" onclick="check('{{=bean.name}}')" tapmode>
          <div>姓名:{{=bean.name}}</div>
          <div>年龄:{{=bean.age}}</div>
          <div>爱好:{{=bean.fun}}</div>
          <img src="../image/add.png" url="{{=bean.url}}" onload="loadImage(this)">
    </div>
    {{~}}
</script>

it:就是你要循环的列表数组
bean:就是数组中的每个bean实体,属性都在里面
index:就是数组的下标position,这些跟Android都一样,很好理解

{{=}}   相当于赋值

还有一种常用的就是if类型的判断

{{? bean.name=='月影'}}
    //吧啦吧啦
{{?}}
{{~it:bean:index}}//开头

{{~}}//结尾
这就是相当于循环那个列表数组了。

3、一进入页面的时候就加载数据:
先来一段模拟ajax请求获取的数据:

var json = [{"name": "张三","age": 31,"fun": "吃东西","url":"http://img05.tooopen.com/images/20140328/sy_57865838889.jpg"},{"name": "李四","age": 44,"fun": "睡觉","url":"http://img.taopic.com/uploads/allimg/120727/201995-120HG1030762.jpg"},{"name": "王五","age": 55,"fun": "打游戏","url":"http://img05.tooopen.com/images/20140328/sy_57865838889.jpg"}];
apiready = function() {
        //编译模板函数
        var tempFn = doT.template($api.byId('temp').innerHTML);
        //数据渲染
        $api.html($api.byId('content'), tempFn(json));
    };

    function loadImage(ele) {
        var url = $api.attr(ele, 'url');
        if (url) {
          api.imageCache({
              url: url
          }, function(ret, err){
              if (ret) {
                ele.src = ret.url;
                $api.attr(ele, 'url','');
              }
          });
        }
    }

    function check(name) {
       api.toast({
           msg: name,
           duration: 2000,
           location: 'bottom'
       });
    }

猜你喜欢

转载自blog.csdn.net/AndroidStudioo/article/details/79898397