我们希望以父子层次结构显示 JSON 数据
var JsonArr = [{
"comment":"Comment 1",
"commentID":1,
"parentID":0,
"children":[{
"comment":"Comment 1-2",
"commentID":2,
"parentID":1,
"children":[{
"comment":"Comment 1-2-2",
"commentID":1,
"parentID":2
}]
}]
},
{
"comment":"Comment 2",
"commentID":4,
"parentID":0
}]
工作中的 JSFiddle : https://jsfiddle.net/6dcdbks4/
任何立即帮助都将非常感激。谢谢。
最佳答案
检查这个fiddle .
不完全是一个树
结构,但我们可以使用css
来模仿它并传递级别
信息
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 = "Full Name";
//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> <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
关于javascript - 以父子层次结构显示 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36026781/