【发布时间】:2016-02-03 01:10:01
【问题描述】:
我有一个评论对象的多维数组,我想出了如何循环遍历第一级对象然后附加它们,但是我很难弄清楚如何将回复与有回复的 cmets。我的策略是使用“if”语句检查是否有回复,然后像我做 cmets 一样遍历回复,但我认为最接近的()函数是问题所在,我不太确定如何访问与该注释对应的 DOM 元素以将其用作选择器。我认为也许另一种策略是使用一个 .each 循环与 cmets 同时处理回复。任何帮助将不胜感激!
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比[]更能代表无回复?
标签: javascript jquery arrays loops append