我有一个评论列表,每个评论都有一个投票计数(正面或负面)。我试图提取前两条评论(基于最高净票数,而不是票数),复制它们的 HTML,并将它们添加到标题为“热门想法”的新部分
我想复制
中编号最高的两条评论的全部内容HTML(过于简化的版本)...每个评论都会重复此操作:
<div class="comment">
<div class="thumbblock">
<div class="ratingtext">
<div>
<span class="num-total" data-voteup="8" data-votedown="4">+4</span>
</div><!-- END random div -->
</div><!-- END ratingtext -->
</div><!-- END thumbblock -->
<p>comment text</p>
</div><!-- END comment -->
jQuery:
jQuery(document).ready(function($) {
//number of top comments to show
var showResults = 2;
//loop through each total rating
//only pull the top two (in this case)
$('span.num-total').slice(0, showResults).each(function(index){
//calculate the net vote total based on data-voteup and data-votedown
var upVotes = $(this).data('voteup');
var downVotes = $(this).data('votedown');
var netVotes = upVotes - downVotes;
//get the HTML for those comments
var commentHTML = $(this).parents('.comment').html();
//append that HTML to the top comment div
$('div.top-comments').append('<div class="comment">' + commentHTML + '</div>');
});
});
在此处查看实时副本:http://jobelty.com/company/apple
jQuery 来自一个名为 top-comments.js 的文件
最佳答案
您在排序之前对列表进行了缩减,因此您最多只能得到恰好位于顶部的两条评论的文本。
该版本获取排名最高的两条评论的完整评论元素,并将其复制到 .top-comments
中:
jQuery(document).ready(function ($) {
//number of top comments to show
var showResults = 2;
var ordered = [];
// grab all the comments
var comments = $('.commentlist .comment');
$.each(comments,
function (i, v) {
// for each comment
var cmt = $(v);
var nums = cmt.find('.num-total');
var upVotes = nums.data('voteup');
var downVotes = nums.data('votedown');
var netVotes = upVotes - downVotes;
var pos = ordered.length;
// find the first place in the ordered list it fits
for (var j = 0; j < ordered.length; ++j) {
if (ordered[j].votes < netVotes) {
pos = j;
break;
}
}
// save element and count for later
var vote = {
'votes': netVotes,
'cmt': cmt
};
ordered[pos] = vote;
});
var n = Math.min(2, ordered.length);
// grab the first (up to) 2 and append to .top-comments
for (var i = 0; i < n; ++i) {
ordered[i].cmt.clone().appendTo($('.top-comments'));
}
});
关于javascript - 如何根据子元素值对父元素进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16311426/