我有一个js函数,我正在努力显示带有测验结果的类别列表。 然而,测验结果是在javascript中计算的,我创建的php表只是调用初始数组而没有结果。 这意味着我可以按数组中的任何内容排序,但我想按测验%排序。 我应该在 js 或 php 中执行此操作吗?
setCategoryOverview: function() {
results.comp.cats = {};
$e.find('.wpProQuiz_catOverview li').each(function() {
var $this = $(this);
var catId = $this.data('category_id');
if(config.catPoints[catId] === undefined) {
$this.hide();
return true;
}
var r = Math.round(catResults[catId] / config.catPoints[catId] * 100 * 100) / 100;
results.comp.cats[catId] = r;
$this.find('.wpProQuiz_catPercent').text(r + '%');
$this.show();
});
},
这是按category_id排序的php表
<div class="wpProQuiz_catOverview" <?php $this->isDisplayNone($this->quiz->isShowCategoryScore()); ?>>
<h4><?php _e('Categories', 'wp-pro-quiz'); ?></h4>
<div style="margin-top: 10px;">
<ol>
<?php foreach($this->category as $cat) {
if(!$cat->getCategoryId()) {
$cat->setCategoryName(__('Not categorized', 'wp-pro-quiz'));
}
?>
<li data-category_id="<?php echo $cat->getCategoryId();?>">
<span class="wpProQuiz_catName"><?php echo $cat->getCategoryName(); ?></span>
<span class="wpProQuiz_catPercent">0%</span>
</li>
<?php } ?>
</ol>
</div>
</div>
正如JayBlanchard所建议的那样,最好的选择是生成百分比并事先进行排序(在服务器端)。但是,这可能不是一种选择。您可以尝试这种方法在客户端(小提琴)中进行命令:
// Pre-calculate the percentages using js as you're doing.
var results = [];
$("ol li").each(function (index, item) {// Store the results in an array of objects.
results.push({
id: $(item).data("category_id"),
name: $(".wpProQuiz_catName", this).text(),
percentage: $(".wpProQuiz_catPercent",this).text()
});
});
results.sort(function(a,b){// Sort the array by percentage.
var numA = +(a.percentage.slice(0,-1)), numB = +(b.percentage.slice(0,-1));
return numB - numA;// Ascending order
});
$("ol li").each(function (index, item) {// Substitute li information acccording to the ordered array.
$(item).attr("data-category_id", results[index].id);
$(".wpProQuiz_catName", this).text(results[index].name);
$(".wpProQuiz_catPercent",this).text(results[index].percentage);
});
它可能可以用更少的循环来完成,因为你正在js中的其他地方计算百分比(你可以利用这一点并在那里创建结果数组)。
希望对您有所帮助。