0

json2html中,如果我在模板中定义了 JSON 中不存在的元素,我想“显示:无;” 或者更好,只是以某种方式排除该行。

示例模板:

{"tag":"div","children":[
    {"tag":"div","html":"First Name: ${first_name}"},
    {"tag":"div","html":"Middle Name: ${middle_name}"},
    {"tag":"div","html":"Last Name: ${last_name}"}
]}

结果:

First Name: John
Middle Name: 
Last Name: Doe

如果 json 中不存在中间名,我不希望它有<div>中间名的条目,而是跳过该行。

我想要什么:

First Name: John
Last Name: Doe
4

2 回答 2

1

一种方法是:

让 div 有 ids/classes,我建议您以这种格式更改模板布局:

{"tag":"div","class":"container","children":[
  {"tag":"div","class":"field","children":[
      {"tag":"span", "html":"First Name:"},
      {"tag":"span","html":"${first_name}"}
    ]
  },
  {"tag":"div","class":"field","children":[
      {"tag":"span", "html":"Middle Name:"},
      {"tag":"span","html":"${middle_name}"}
    ]
  },
  {"tag":"div","class":"field","children":[
      {"tag":"span", "html":"Last Name:"},
      {"tag":"span","html":"${last_name}"}
    ]
  }
]}

处理完之后,您可以编写一个小代码(jquery),如下所示:

 $(".container div").each(function(){
   var childs = $(this).children();
   if($(childs[1]).is(":empty")){
     $(this).hide();
   }
 });

我认为它应该工作。

希望能帮助到你

于 2016-01-26T22:43:22.597 回答
0

您也可以在 json2html 模板中这样做

{"tag":"div","children":[
   {"tag":"div","html":"First Name: ${first_name}"},
   {"tag":"div","html":"Middle Name: ${middle_name}","class":function(){
      if(!this.middle_name) return("hide");
   }},
   {"tag":"div","html":"Last Name: ${last_name}"}]}

然后只需添加这个 css

.hide {display:none;}
于 2016-05-17T21:09:01.017 回答