我想創建一個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