简体   繁体   中英

How to build inline rating using JavaScript or jQuery?

I need to build inline rating for tv shows for example. Max rating I put in jQuery code, current rating in html document. This is how I found the way to do this.

 $(document).ready(function() { var maxRating = $('.rate-line').width(); var maxRating = 6; //max-rating var currentRatingFirst = $('.first-rd').text(); var calc = (currentRatingFirst / maxRating) * 100 + "%"; $('.first-rl span.fill').width(calc); }); 
 .rate-line { border: 1px solid #bababa; background: #fff; position: relative; vertical-align: middle; margin-right: 1.25em; overflow: hidden; width: 50%; height: 20px; } .rate-line, .rate-data, .fill { display:inline-block; } .fill { background: #ff6292; height: 22px; position: absolute; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div> <span class="rate-line first-rl"> <span class="fill"></span> </span> <span class="rate-data first-rd">4.56</span> </div> 

But, I need to create 6 rating lines for this month, then 6 for next and so on. And every time I must give new unique classes to make it work. And code becomes huge. And one more, all this rating nested to bootstrap carousel items and when I duplicate it nothing works .I'm not good in JavaScript at all and I'm asking your help. Would you please tell me how to make it work correctly and make it easier?

In this case it makes sense to create basin custom plugin, so you can easily reuse it without duplicating code.

Here is a very basic example of how you can extend jQuery prototype with a new method:

 $.fn.rating = function(options) { return this.each(function() { var maxRating = $(this).find('.rate-line').width(); var maxRating = 6; var currentRatingFirst = $(this).find('.first-rd').text(); var calc = (currentRatingFirst / maxRating) * 100 + "%"; $(this).find('.first-rl span.fill').width(calc); }); }; $(document).ready(function () { $('.rating').rating(); }); 
 .rate-line { border: 1px solid #bababa; background: #fff; position: relative; vertical-align: middle; margin-right: 1.25em; overflow: hidden; width: 50%; height: 20px; } .rate-line, .rate-data, .fill { display:inline-block; } .fill { background: #ff6292; height: 22px; position: absolute; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="rating"> <span class="rate-line first-rl"> <span class="fill"></span> </span> <span class="rate-data first-rd">4.56</span> </div> <div class="rating"> <span class="rate-line first-rl"> <span class="fill"></span> </span> <span class="rate-data first-rd">3.21</span> </div> 

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