【实用代码片段】将json数据绑定到html元素 (转)

本文介绍了一个jQuery的扩展方法,该方法允许开发者通过属性[json-bind]和[json-bind-attr]将JSON数据绑定到DOM元素中,从而简化了页面元素的数据填充过程。

jQuery扩展

jQuery.fn.extend({
  'jsonBind':function(json){
    var dom=this;
    dom.find('[json-bind]').each(function(){
      var val=$.trim(json[$(this).attr('json-bind')]);
      if(val!='') $(this).html(val);
    });
    dom.find('[json-bind-attr]').each(function(){
      var s=$(this).attr('json-bind-attr').split('|');
      if($(this).attr(s[0]).indexOf('{%s}')>-1){
        $(this).attr(s[0],$(this).attr(s[0]).replace('{%s}',json[s[1]]));
      }else{
        $(this).attr(s[0],json[s[1]]);
      }
    });
  }
});

使用方法

<ul>
  <li json-bind="name"></li>
  <li json-bind="year"></li>
  <li json-bind="birth"></li>
  <li json-bind="work"></li>
  <li><a href="#" json-bind-attr="href|website" json-bind="website"></a></li>
  <li><a href="http://zcc.ren/article/{%s}" json-bind-attr="href|article">来源</a></li>
</ul>
$('ul').jsonBind({'name':'canson','year':100,'birth':'1970-01-01','work':'webfront','website':'http://zcc.ren/','article':140});

 

转载于:https://www.cnblogs.com/shy1766IT/p/7306622.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值