$.each & template

Template using jQuery:

<script id="blogTemplate" type="lines/template">
    <h2>{{title}}</h2>
    <img src={{thunbnail}} alt={{title}}/>
</script>
(function(){
     var content=[
      {
             title:"my first blog post",
             thunbnail:"https://tutsplus.s3.amazonaws.com/previewimages/nycmeetup.png",
          },
         {
             title:'my second blog post',
             thunbnail: 'http://d2o0t5hpnwv4c1.cloudfront.net/2053_userauth/Tutorial_preview.jpg',
          }
      ],
      template=$.trim($("#blogTemplate").html()) ;
                
      $.each(content,function(index,obj){
          var temp = template.replace(/{{title}}/ig,obj.title).replace(/{{thunbnail}}/ig,obj.thunbnail);

          $(document.body).append(temp);
     })
}());

 

and so if the content array contains more than 50 items ,and in the each method it will iterate over all these items,and as you can see, this will be so bad for the perfomance,so instead we will create another variable "flag" to get all the content in the array,when this step is finished,the put all of it into the DOM,

(function(){
    var content=[
        {
           title:"my first blog post",
           thunbnail:"https://tutsplus.s3.amazonaws.com/previewimages/nycmeetup.png",
          },
          {
            title:'my second blog post',
            thunbnail: 'http://d2o0t5hpnwv4c1.cloudfront.net/2053_userauth/Tutorial_preview.jpg',
          }
       ],
       template=$.trim($("#blogTemplate").html()),
       flag = '';
                
       $.each(content,function(index,obj){
       flag += template.replace(/{{title}}/ig,obj.title).replace(/{{thunbnail}}/ig,obj.thunbnail);                    
  })
  $(document.body).append(flag);
}());

 

jquery api for .each(): http://api.jquery.com/each/

juqey api for $.each(): http://api.jquery.com/jQuery.each/

 

 

Template using UnderscoreJs  

http://underscorejs.org/

<script type="text/template" id='template'>
    <h1><%= home %></h1>
</script>

underscore的template有两种写法: 

第一种:

    var tepl = _.template($('#template').html());
    var compile = tepl({'home':"do"});
    console.log(compile);

第一种显而易见是将script标签内的模板内容进行编译,返回一个function,然后再对值进行操作。返回的function如下:

    function (data) {
      return render.call(this, data, _);
    } 

第二种:

    var data = {'home':"myHome"};
    var template = _.template($('#template').html(),data);
    console.log(template)

直接传入值对填入选取到的模板

 

两种方法没区别,只是根据需要会用这个或者那个,其中还是使用jQuery作为DOM的选择器,”_.template()“属于

 

 

 

 

转载于:https://www.cnblogs.com/strangeline/archive/2012/07/03/2575449.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值