我有代码可以根据评级呈现五星级评级,我认为这对每个人来说都很容易,但我不知道如何让这段代码变得更好。
@TJ Crowder 有解决这个问题的想法:
// Flags for whether to show stars, based on `average` being
// a fractional number `0 <= average < 5`
var stars = [
average > 0,
average > 1,
average > 2,
average > 3,
average > 4
];
如何实现这个或任何人有任何想法使这个代码更好?
var result = '';
var one_star = '';
var two_star = '';
var three_star = '';
var four_star = '';
var five_star = '';
if(data == 0) {}
else if(data == 1) {
one_star = 'star-rating-on';
two_star = '';
three_star = '';
four_star = '';
five_star = '';
}
else if(data == 2) {
one_star = 'star-rating-on';
two_star = 'star-rating-on';
three_star = '';
four_star = '';
five_star = '';
}
else if(data == 3) {
one_star = 'star-rating-on';
two_star = 'star-rating-on';
three_star = 'star-rating-on';
four_star = '';
five_star = '';
}
else if(data == 4) {
one_star = 'star-rating-on';
two_star = 'star-rating-on';
three_star = 'star-rating-on';
four_star = 'star-rating-on';
five_star = '';
}
else if(data == 5) {
one_star = 'star-rating-on';
two_star = 'star-rating-on';
three_star = 'star-rating-on';
four_star = 'star-rating-on';
five_star = 'star-rating-on';
}
result += '<span class="star-rating-control">';
result += '<div class="star-rating rater-5 star star-rating-applied star-rating-readonly '+ one_star +'"><a title="Poor">1</a></div>';
result += '<div class="star-rating rater-5 star star-rating-applied star-rating-readonly '+ two_star +'"><a title="OK/Fair">2</a></div>';
result += '<div class="star-rating rater-5 star star-rating-applied star-rating-readonly '+ three_star +'"><a title="Good">3</a></div>';
result += '<div class="star-rating rater-5 star star-rating-applied star-rating-readonly '+ four_star +'"><a title="Great">4</a></div>';
result += '<div class="star-rating rater-5 star star-rating-applied star-rating-readonly '+ five_star +'"><a title="Excellent">5</a></div>';
result += '</span>';