首页 > 解决方案 > 跨度点击功能不起作用(很棒的字体星级评分系统)

问题描述

编码器。

我正在尝试使用基于星级的评级系统制作一个简单的相册。我正在使用 W3 上提供的示例,使用 Font Awesome 来完成这项工作。但是,这是无响应的,我希望用户能够通过单击星号来更改评分。IE 如果他点击第四颗星,它将变成四颗星,以此类推。

问题是,我的点击功能没有响应。进一步看,问题似乎在于 span 标签里面没有任何东西。有没有办法解决这个问题,或者我必须使用字体真棒以外的其他东西来获得响应式星级评分系统?

<!DOCTYPE html>
<html lang ="en-us">
<head>
 <meta charset="UTF-8">
  <title>Bomb Defuser</title>

   <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <style>
 .checked {
   color: orange;
 }

 img {
 height:400px;
 width: 400px;
 }

 span {
 display:inline;
 }
 </style>

 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font- 
 awesome/4.7.0/css/font-awesome.min.css">

 <script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
 </script>
 </head>

 <body>


  <img src = "camera.png"></img>
 <br>
 <div id = "rating1">
 <span class="fa fa-star checked"></span>
 <span class="fa fa-star checked"></span>
 <span class="fa fa-star checked"></span>
 <span class="fa fa-star"></span>
 <span class="fa fa-star"></span>
 </div>
 <hr>
 <br>
 <br>


 <img src = "bomb.png"></img>
 <br>
 <div id = "rating2">
 <span class="fa fa-star checked"></span>
 <span class="fa fa-star checked"></span>
 <span class="fa fa-star checked"></span>
 <span class="fa fa-star"></span>
 <span class="fa fa-star"></span>
 </div>
 <hr>
 <br>
 <br>



 <img src = "dummy_image.png"></img>
 <br>
 <div id = "rating3">
 <span class="fa fa-star checked"></span>
 <span class="fa fa-star checked"></span>
 <span class="fa fa-star checked"></span>
 <span class="fa fa-star"></span>
 <span class="fa fa-star"></span>
 </div>
 <hr>
 <br>
 <br>


 <script>
 //now what I'm trying to do, is say if you click the nth child of a div, so 
 //does it and all previous children.
 //the number that represents the n in nth can be like the array.length is 
 //in a for loop.
 //okay, first thing is first.  We have to set up an onClick event.

 $("span").click(function(){
     $(this).prop('checked', true);
  });


  </script>

  </body>
  </html>

标签: jqueryhtmlfunctionclickfont-awesome

解决方案


用于index()获取当前星索引和:lt伪选择器选择以前的星

$('.fa-star').click(function(){
    var i = $(this).index();
    $('.checked').removeClass('checked');
    $('.fa-star:lt('+(i+1)+')').addClass('checked');
});
.checked {color:orange};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <div id = "rating1">
 <span class="fa fa-star"></span>
 <span class="fa fa-star"></span>
 <span class="fa fa-star"></span>
 <span class="fa fa-star"></span>
 <span class="fa fa-star"></span>
 </div>


推荐阅读