我想在JavaScript中创建一个星级,默认值是5,我会降到1,但我不明白如何从1到5填充。
这是我的代码: -
$(".star").click(function(){
var starselect = $(this).attr("id");
for( var j = 5 ; j>starselect ; j--)
{
$("#"+j).removeClass("starchecked");
}
if( j < starselect+1 ){
$("#"+j).addClass("starchecked");
}
$(".review-star").attr("data-rating",starselect);
});
答案 0 :(得分:0)
根据我的评论,我会使用css执行此操作,但如果您需要使用js,那么我会混合使用nextAll
,prevAll
和andSelf
- 请参阅代码
var $stars = $(".star")
$stars.click(function() {
var $star = $(this);
if ($star.hasClass('checked')) {
// if current clicked star is checked
if ($star.next().hasClass('checked')) {
// check if next star is also checked
$star.nextAll().removeClass('checked'); // if next is then disable all following
} else {
$star.nextAll().andSelf().removeClass('checked'); // if not then disable self and all after (shouldn't need all after, but just in case)
}
$star.prevAll().addClass('checked'); // check all before
// if you just want to remove all stars on click of an already checked box, remove the above 2 lines and just ue the below:
// $stars.removeClass('checked');
} else {
$star.nextAll().removeClass('checked'); // remove checked from all following the clicked
$star.prevAll().andSelf().addClass('checked'); // add checked to this and all previous
}
var starselect = $stars.index($star) + 1; // get current star rating
$(".review-star").attr("data-rating", starselect);
console.log(starselect);
});
&#13;
.star {
border: 1px solid black;
width: 20px;
height: 20px;
display: inline-block;
}
.checked {
background-color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="star">1</span>
<span class="star">2</span>
<span class="star">3</span>
<span class="star">4</span>
<span class="star">5</span>
&#13;