JSFiddle - React, Tailwind, and code Playground
by cherishpeace
HTML
<div id="11" style="width:600px;height:400px;padding:10px;">
JavaScript
var myTree={
container:null,
//deep:0,
padding_size:15,
init:function(id,json){
this.container = $("#"+id);
var str = this.format(json);
this.render(str);
this.bindEvent();
},
format:function(json){
//this.deep++;
var str="<div style='padding-left:"+this.padding_size+"px'>";
for (var i in json) {
if (!json[i].children) {
str+='<span> </span><span style="padding-left:5px;cursor:pointer;">'+json[i].name+'</span><br>';
}else{
str+='<span style="cursor:pointer;" class="treeItemPre">-</span><span style="padding-left:5px;cursor:pointer;" class="treeItem">'+json[i].name+'</span><br>'+this.format(json[i].children);
}
};
str+="</div>";
// this.deep--;
return str;
},
render:function(str){
this.container.html(str);
},
bindEvent:function(){
this.container.find(".treeItem").live('click', function() {
var t = $(this).prev().html() == "+" ? "-" : "+";
$(this).prev().html(t);
$(this).nextAll("div").first().slideToggle(100);
});
this.container.find(".treeItemPre").live('click', function() {
var t = $(this).html() == "+" ? "-" : "+";
$(this).html(t);
$(this).nextAll("div").first().slideToggle(100);
});
this.container.find("span").hover(function(){
$(this).css("color","#666");
},function(){
$(this).css("color","#000");
});
}
};
$(function() {
var j={
"1":{"name":"node1","children":{
"1_1":{"name":"node1_1"},
"1_2":{"name":"node1_2"}
}},
"2":{"name":"node2"},
"3":{
"name":"node3",
"children":{
"3_1":{"name":"node3_1"},
"3_2":{"name":"node3_2","children":{
"3_2_1":{"name":"node3_2_1"},
"3_2_2":{"name":"node3_2_2"}
}}
}}
};
myTree.init('11',j);
});