我有一個多維數組的評論對象,我想出瞭如何循環通過第一級對象然後追加它們,但我有一個真正的很難弄清楚如何將回復與有回覆的評論一起提交。我的策略是使用一個「if」語句來檢查是否有回覆,然後像回覆評論一樣循環回覆,但我認爲最接近的()函數是問題,我不太確定如何訪問與該註釋相對應的DOM元素以將其用作選擇器。我認爲也許另一個策略是用一個.each循環同時處理回覆。任何幫助將不勝感激!用循環在多維數組中追加內部對象
var myCommentArray = [
{
_id: "888888888888888888",
index: 1,
name: "Perez",
message: "First Comment .......",
subject: "enim officias",
replies: [ // notice this comment has replies (just 1 but it is still an array)
{
_id: "77777777777777777777",
index: 0,
name: "Reply to First Comment Ines for Perez",
message: "...",
subject: "reply subject consequat"
}
]
},
{
_id: "999999999999",
index: 0,
name: "Shelton",
message: "2nd Comment....a",
subject: "enim irure",
replies: null // notice this comment has no replies and as such is null. this is better than an empty array
},
{
_id: "666666666666666666",
index: 2,
name: "Perez",
message: "3rd Comment.......",
subject: "enim officias",
replies: [
{
_id: "55555555555555555555",
index: 0,
name: "1st Reply to 3rd Comment",
message: "...",
subject: "reply subject consequat"
},
{
_id: "44444444444444444444",
index: 1,
name: "2nd Reply to 3rd Comment",
message: "...",
subject: "reply subject consequat"
}
]
}
];
sabio.page.processComments = function (i, currentComment) {
var commentsFormat = '<br> <div class="comment-avatar media-left"> <img src="http://placehold.it/50x50" alt="avatar">' +
'</div><div class="comment-content media-body clearfix"> <div class="comment-avatar media-left"></div><h3 class="media-heading">' +
currentComment.subject + '</h3> <div class="comment-meta">By ' + currentComment.name + '</div> <div class="comment-body"> <p>'
+ currentComment.message + '</p><a href="#" class="replyButton">' +
'<i class="fa fa-reply"> </i> Reply </a> </div> </div>';
$('.comments').append(commentsFormat);
};
$.each(myCommentArray, sabio.page.processComments);
sabio.page.processReplies = function (j, currentComment) {
var repliesFormat = '<br> <div class="comment-avatar media-left"> <img src="http://placehold.it/50x50" alt="avatar">' +
'</div><div class="comment-content media-body clearfix"> <div class="comment-avatar media-left"></div><h3 class="media-heading">' + currentComment.subject + '</h3> <div class="comment-meta">By ' + currentComment.name + '</div> <div class="comment-body"> <p>' + currentComment.message + '</p><a href="#" class="btn btn-gray more reply">' +
'<i class="fa fa-reply"> </i> Reply </a> </div> </div>';
var closestComment= $(currentComment).closest();
$(closestComment).append(repliesFormat);
});
if (myCommentArray.replies) {
$.each(myCommentArray.replies, sabio.page.processReplies);
};
你覺得爲什麼'null'是沒有回覆比'[]'更好的表示? – 76484