我想创建一个select
框,并使用我的扁平JSON数据显示项目及其深度。以下图片与Joomla CMS在层次类别中使用PHP的情况相同。从对象数组创建模拟分层选择框
我的样本数据是这样(注意,深度为无穷大):
[{
"id": 1,
"parent": "0",
"text": "Doctors"
}, {
"id": 2,
"parent": "0",
"text": "Clinics"
}, {
"id": 3,
"parent": 1,
"text": "General doctors"
}, {
"id": 4,
"parent": 1,
"text": "Experts"
}, {
"id": 5,
"parent": 4,
"text": "Children diseases specialist"
}, {
"id": 6,
"parent": 4,
"text": "Otorhinolaryngology"
}]
我写了下面的代码,我通过调用Data.createTreeOptions(items);
使用它和它的工作,但我get是原始数组项目排序的选项列表。我想要项目在parent - children
加载像图片中的那些。
var Data = {
createTreeOptions: function (items) {
if (!items.length)
return '';
var html = '', children = [], l;
$.each(items, function() {
l = (typeof children[this.parent] !== "undefined") ? children[this.parent] : [];
l.push(this);
children[this.parent] = l;
});
var tree = Data.treeRecurse(0, '', [], children, 0);
$.each(tree, function() {
if (typeof this.id !== "undefined")
html += '<option value="' + this.id + '" data-parent="' + this.parent + '">' + this.treemenu + '</option>';
});
return html;
}
, treeRecurse: function (id, indent, list, children, level) {
if (typeof children[id] !== "undefined" && children[id]) {
$.each(children[id], function() {
var v = this;
var id = v.id;
if (v.parent === 0)
text = v.text;
else
text = '|_ ' + v.text;
list[id] = v;
list[id].treemenu = indent + text;
list[id].children = (typeof children[id] !== "undefined") ? children[id].length : 0;
level++;
list = Data.treeRecurse(id, indent + ' -', list, children, level);
});
}
return list;
}
}
首先要做的:打开你的文本编辑器,并开始创建的代码。第二:显示你卡在哪里。第三:你会得到一个很好和准确的答案。你问的方式实在太宽泛。 – skobaljic
@skobaljic我加了我的代码,我想我可以通过不显示我自己的代码找到比我更好的解决方案。 –
我不明白这个语言,但基本上你想用'-'来缩进这些项目,例如,基于父子关系?这是主要目标? – skobaljic