且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在父子层次结构中显示JSON数据

更新时间:2023-11-01 17:16:04

检查这个小提琴

不完全是结构,但我们可以使用 css 并传递传递级别信息

not exactly a tree structure but we can mimic it using css and passing passing level information

function showComments(comments,level){//Extra parameter for level information
 for(var i = 0; i < comments.length; i++) {
     commentsContainer = loadComment(comments[i], commentsContainer,level)//render comment along with level information
    if (comments[i]['children'] && comments[i]['children'].length) {
      showComments(comments[i]['children'],level+1)//next level for children
    }
  }
}

function loadComment(commentObj, commentsContainer,level){//level of node
    var profileFullName = "Rohit Jindal";
    //add some padding multiplied with level for each comment element
    var commentHTML = '<div class="commentbox" style="padding-left:'+(level*100)+'px;"><div class="commentphoto"><a href="#123"><img src="https://graph.facebook.com/100000816365798/picture?type=square"></a></div><div class="commentcontent"><a href="#123"><strong>' + profileFullName + '</strong></a> &nbsp;<small>Just now</small><br>' + commentObj.comment + '<br><a name="replyComment" commentid="' + commentObj.commentID + '">Reply</a><span id="votescore-' + commentObj.commentID + '" class="votescore"></span></div></div>';
    commentsContainer.append(commentHTML);
    return commentsContainer;
}

showComments(JsonArr,0);//call showComment with initial level 0