I came across this simple star rating system with font awesome. I have a problem though. In a page where there are multiple star blocks for rating they all get called at the same time. How can I prevent this behavior and have only the intended block to apply the clicked stars?
fiddle: http://jsfiddle.net/VGx6r/
HTML
<div class="star-rating">
<span class="fa fa-star-o" data-rating="1"></span>
<span class="fa fa-star-o" data-rating="2"></span>
<span class="fa fa-star-o" data-rating="3"></span>
<span class="fa fa-star-o" data-rating="4"></span>
<span class="fa fa-star-o" data-rating="5"></span>
<input type="hidden" name="whatever" class="rating-value" value="3">
</div>
CSS
.star-rating {
line-height:32px;
font-size:1.25em;
cursor: pointer;
}
Javascript:
var $star_rating = $('.star-rating .fa');
var SetRatingStar = function() {
return $star_rating.each(function() {
if (parseInt($star_rating.siblings('input.rating-value').val()) >= parseInt($(this).data('rating'))) {
return $(this).removeClass('fa-star-o').addClass('fa-star');
} else {
return $(this).removeClass('fa-star').addClass('fa-star-o');
}
});
};
$star_rating.on('click', function() {
$star_rating.siblings('input.rating-value').val($(this).data('rating'));
return SetRatingStar();
});
SetRatingStar();
It's because of this:
var $star_rating = $('.star-rating .fa');
It is applying the function to every star-rating class.
You would need to modify that selector to specify which one to change. You could pass the element into setStarRating
Example:
return SetStarRating($(this));
and then use that in the SetRatingStar
method
In response to your comment. I'm feeling generous so here you go:
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.