gpt4 book ai didi

javascript - json2html如何在字段不存在时排除行

转载 作者:行者123 更新时间:2023-12-03 07:50:15 26 4
gpt4 key购买 nike

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

示例模板:

{"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

最佳答案

实现此目的的一种方法是:

让 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();
}
});

我认为它应该有效。

希望对你有帮助

关于javascript - json2html如何在字段不存在时排除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35024509/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com