首页 > 解决方案 > 我想在 JavaScript 中创建星级。

问题描述

我想在 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);
});

标签: javascriptjquery

解决方案


根据我的评论,我会使用 css 来执行此操作,但如果您需要使用 js,那么我会使用nextAll,prevAllandSelf- 的混合使用,请参阅代码中的注释

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);
});
.star {
  border: 1px solid black;
  width: 20px;
  height: 20px;
  display: inline-block;
}

.checked {
  background-color: red;
}
<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>


推荐阅读