如何根據「id」和「pid」從我的JSON創建嵌套菜單(帶有「sub-sub-sub ...- n」)項目?json的多級嵌套菜單
代碼細節:
id - item ID
lvl - level of the item
pid - parent ID of the item
pos - position of the item
nm - name of the item
JSON:
[{"id":1,"lvl":0,"pid":0,"pos":0,"nm":"HomeTree"},
{"id":5,"lvl":1,"pid":1,"pos":0,"nm":"Books"},
{"id":2,"lvl":1,"pid":1,"pos":1,"nm":"Jobs"},
{"id":16,"lvl":1,"pid":1,"pos":2,"nm":"Music"},
{"id":17,"lvl":2,"pid":16,"pos":0,"nm":"Relax Sets"},
{"id":12,"lvl":1,"pid":1,"pos":3,"nm":"Cars"},
{"id":13,"lvl":2,"pid":12,"pos":0,"nm":"BMW"},
{"id":14,"lvl":1,"pid":1,"pos":4,"nm":"Web"},
{"id":15,"lvl":2,"pid":14,"pos":0,"nm":"PHP Analytics"},
{"id":18,"lvl":1,"pid":1,"pos":5,"nm":"Hardware"},
{"id":19,"lvl":2,"pid":18,"pos":0,"nm":"EVGA SR2 Upgrades"},
{"id":31,"lvl":2,"pid":18,"pos":1,"nm":"Keyboards"},
{"id":20,"lvl":1,"pid":1,"pos":6,"nm":"Movies"},
{"id":21,"lvl":1,"pid":1,"pos":7,"nm":"Games"},
{"id":22,"lvl":1,"pid":1,"pos":8,"nm":"Robots"},
{"id":25,"lvl":1,"pid":1,"pos":9,"nm":"Magazines"},
{"id":26,"lvl":2,"pid":25,"pos":0,"nm":"IT Security"},
{"id":27,"lvl":1,"pid":1,"pos":10,"nm":"Management"},
{"id":28,"lvl":2,"pid":27,"pos":0,"nm":"Holacracy"},
{"id":29,"lvl":3,"pid":28,"pos":0,"nm":"Testtt"}]
我需要什麼:
HomeTree
Books
Jobs
Music
Relax Sets
Cars
BMW
Web
PHP Analytics
Hardware
EVGA SR2 Upgrades
Keyboards
Movies
Games
Robots
Magazines
IT Security
Management
Holacracy
Testtt
我當前的代碼:
$.ajax({
url: './jstree_head.php?operation=full_tree',
data: "",
dataType: 'json',
success: function(data)
{
var output="<br />";
for (var i in data)
{
var rid = data[i].id;
var rpid = data[i].pid;
var rlvl = data[i].lvl;
var rnm = data[i].nm;
var nest = ' ';
if(rpid > 1) {
nm = nest+rnm+'<br>';
}
else {nm = rnm+'<br>';}
output+='' + nm + '';
}
$('#content').html(output);
}
});
現在我不能說明深層次的子層次,那麼正確的方法是什麼?
--- UPDATE ---
我想的是:
var nest = ' ';
if(rpid > 1) {
nm = nest+rnm+'<br>';
}
else {nm = rnm+'<br>';}
output+='' + nm + '';
但這只是一個級別的父項。
以我當前的代碼:'VAR巢= ' '; if(rpid> 1)nm = nest + rnm +'
'; } else {nm = rnm +'
';} output + =''+ nm +'';' – mastrdevl
請更新您的問題, – Soviut
謝謝!我已經做了。 – mastrdevl