代码建议-使用$.each()设置一种使用表

Code suggestions - using $.each() to set a kind of use meter

本文关键字:一种 设置 使用 each 代码      更新时间:2023-09-26

希望这里能有一个快速的同行评审。一个同事和我建立了一个视频popchart插件的客户在韩国(这里是测试网站- http://izepic.com/kpopcharts/)。我的问题与每个视频播放器头部的活动表有关。因此,我编写了下面的js来检查每个社交互动数字,确定它们在交互总数中的百分比,然后在仪表本身中设置每种类型的宽度。注意,每种交互类型都需要特异性。

$('.bkp-meter').each(function(index){
// find participation type base numbers
var voteTotal = parseInt($('.bkp-vote-total').eq(index).text());
var facebookTotal = parseInt($('.bkp-facebook-total').eq(index).text());
var twitterTotal = parseInt($('.bkp-twitter-total').eq(index).text());
var googleTotal = parseInt($('.bkp-google-total').eq(index).text());
var commentTotal = parseInt($('.bkp-comment-total').eq(index).text());
var scoreTotal = voteTotal + facebookTotal + twitterTotal + googleTotal + commentTotal;
// find participation type ratio
var votePercentage = (voteTotal / scoreTotal) * 100;
var facebookPercentage = (facebookTotal / scoreTotal) * 100;
var twitterPercentage = (twitterTotal / scoreTotal) * 100;
var googlePercentage = (googleTotal / scoreTotal) * 100;
var commentPercentage = (commentTotal / scoreTotal) * 100;
if(scoreTotal > 2) {
// set meter widths for each participation type
$('.bkp-meter-votes').eq(index).css('width', (votePercentage.toFixed(0) - 2) + "%");
$('.bkp-meter-fb').eq(index).css('width',facebookPercentage.toFixed(0) + "%");
$('.bkp-meter-twitter').eq(index).css('width',twitterPercentage.toFixed(0) + "%");
$('.bkp-meter-google').eq(index).css('width',googlePercentage.toFixed(0) + "%");
$('.bkp-meter-comments').eq(index).css('width',(commentPercentage.toFixed(0)) + "%");
} else {
$(this).parent().parent().addClass('novotes');
}
});

我的问题是:有没有一种更快、更干净的方法来做到这一点?我的意思是,它工作得很好,所以问题解决了,但感觉很粗暴……为了我自己的改进,我想知道是否有更有效的方法,以及我可能会遇到什么样的问题。注意-百分比不必是完美的…他们只需要让用户快速了解其他人对该视频做了什么。

谢谢

作为一名程序员,当存在不止一件事情时,您应该进行泛化:

var participationTypes = ['vote', 'facebook', 'twitter', 'google', 'comment'];
$('.bkp-meter').each(function() {
    var meter = $(this);
    var scores = {};
    var scoreTotal = 0;
    $.each(participationTypes, function() {
        scores[this] = parseInt(meter.find('.bkp-'+this+'-total').text());
        scoreTotal += scores[this];
    });
    if(scoreTotal > 2)
        $.each(participationTypes, function() {
            meter.find('.bkp-meter-'+this).width(
                Math.round(scores[this] / scoreTotal * 100) + '%'
            );
        });
    else
        meter.parent().parent().addClass('novotes');
});

$.each()返回两个参数,一个是index,另一个是对象本身。你可以通过只在该上下文中搜索来优化选择器。

$('.bkp-meter').each(function(index, meter){
...
$('.bkp-meter-votes', meter).css('width', (votePercentage.toFixed(0) - 2) + "%");
$('.bkp-meter-fb', meter).css('width',facebookPercentage.toFixed(0) + "%");
...
});

同样的事情也适用于$('.bkp-vote-total').eq(index)位的第一个块。

还需要注意的是,类选择器在不支持getElementByClass的浏览器(即IE8和更低版本)中非常慢,所以如果担心的话,要小心单独使用它们。始终提供上下文:$('#container .bkp-meter')

相关文章: