简体   繁体   中英

display images based on rating in javascript

I have a script which displays ratings out of 10:

overallRating = Ratings.RoundToHalf( ( convenience + quality + rebook )/3 );

This returns a value such as 1 or 1.5 etc.

What I would like to do is display star images based on the returned rating, but only up to 5 stars instead of 10.

How would I do this by using an if statement, for example:

if overallRating = 1 {
row = "<img src='star1.png' />";
}

if overallRating = 1.5 {
row = "<img src='star1.png' />";
}

etc

This is the part of my script that displays the results:

if ( overallRating > 0 )
row = row + '<td align="center">' + overallRating + "/10</td>";
else 
row = row + '<td align="center">N/A</td>';

row = row + "</tr>";

Any help would be great! Thanks.

Generally developers use a sprite image in the background of a div and position the background-image of the stars.

If you wanted to show 1-5 stars and round down to the nearest star like how you originally wanted to approach the problem, you can write something like this:

var rating = Math.floor(overallRating);
if (rating) {
    var img = "";
    for(var i=0; i < rating; i++) {
    img = img + "<img src='star1.png' />";
    }
    row = '<tr>' + '<td align="center">' + img + "/10</td>";
}
else {
    row = '<tr>' + '<td align="center">N/A</td>';
}
row = row + "</tr>";

If you want to create a rating system the proper way, please check out this link: Turn a number into star rating display using jQuery and CSS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM