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

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