【发布时间】:2025-12-18 00:40:02
【问题描述】:
我有一个 JSON 对象,我可以在单击时循环访问它,我用它以 HTML 格式显示给最终用户。目前显示非常通用,并将所有内容都放在 P 标签中。
我想做的是根据其键构建自定义元素,并且如果其键值为空,则不显示项目。到目前为止,这是我正在使用的:
var obj = {
"x": 1409529600000,
"y": 730,
"pf": [
{
"sd": "this is some text",
"ld": "here guy"
},
{
"sd": "here is more yo",
"ld": "ld over here"
}
],
"nf": [
{
"sd": "im in the nf array",
"ld": "Hi mom"
},
{
"sd": "me too!",
"ld": "Where am i"
}
],
"t": [
"here is a tip",
"how about the other tip"
]
};
(function(){
document
.getElementById('myObj')
.addEventListener("click", showObjData);
}());
function buildData(content) {
var data = document.createElement('p');
data.innerHTML = content;
return data;
}
function goThroughObj(obj) {
var htmlObj,
property;
for (property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] === "object") {
goThroughObj(obj[property]);
} else {
document
.getElementById('showObj')
.appendChild(buildData(obj[property]));
}
}
}
}
function showObjData() {
var key,
title,
element = document.getElementById('showObj');
// clear innerHTML in case user click more than once
element.innerHTML='';
for (key in obj) {
// skip anything that is not an array, ie: x, y
if (obj[key] instanceof Array) {
title = '<br/>From ' + key + ' : ';
element.appendChild(buildData(title));
// use recursive function
// to go through each keys/properties
goThroughObj(obj[key]);
}
}
};
这里是与它一起使用的 jfiddle http://jsfiddle.net/kzcm32g8/6/
如您所见,每个条目都放置在 P 标记内。相反,我想要的是每个键更定制的东西。例如,它看起来更像:
- 如果 pf 存在,则使用自定义字符串绑定到
<h2> - 如果 sd 存在于 pf 中绑定值到
<p class="first"> - 如果 ld 存在于 pf 中绑定值到
<p class="second">
- 如果 nf 存在,则使用自定义字符串绑定到
<h2> - 如果 sd 存在于 pf 绑定值到
<p class="first"> - 如果 ld 存在于 pf 中绑定值到
<p class="second">
- 如果 t 存在,则使用自定义字符串绑定到
<h2> - 将数组值绑定到
<p>
这个想法是允许我将返回的数据分配给我设置样式的模板。如果值为 null,我只会将它们从该模板中排除。
【问题讨论】:
-
使用 Angular 等 JavaScript MVC 库可以更轻松地进行这种数据绑定。
-
我完全同意,但是对于这种特殊情况,无法使用库。
标签: javascript jquery arrays json object