3

-- 链接已删除 --

如何使用带有 for 循环的 Jquery 将上述网站中的数字转换为星星,以添加多少星星,以及向上舍入、向下舍入功能。

我更喜欢使用此示例进行舍入:

  • 如果低于 3.25,则为 3.0;这将包括 3 颗满星,2 颗空星
  • 如果介于 3.25 和 3.75 之间,则为 3.5;这将包括 3 颗满星和 1 颗半星、1 颗空星
  • 如果高于 3.75,则为 4.0;这将包括 4 颗满星,1 颗空星
4

1 回答 1

2

您需要将评级列表更新为可选容器,并且评级需要封装在它自己的选择器中。

HTML:

<ul class="ratings">
  <li>Overall Rating Data (no stars): <span>3.14285714286</span></li>
  <li>Overall Grounds Data (no stars): <span>3.14285714286</span></li>
  <li>Overall Price Data (no stars): <span>3.14285714286</span></li>
  <li>Overall Staff Data (no stars): <span>3</span></li>
  <li>Overall Maintenance Data (no stars): <span>2.85714285714</span></li>
  <li>Overall Noise Data (no stars): <span>3.42857142857</span></li>
  <li>Overall Amenities Data (no stars): <span>3.57142857143</span></li>
  <li>Overall Location Data (no stars): <span>3.28571428571</span></li>
  <li>Overall Parking Data (no stars): <span>3.28571428571</span></li>
  <li>Overall Safety Data (no stars): <span>3</span></li>
</ul>

JS:

$(document).ready(function() {
  $('ul.ratings li').each(function() {
    var $el = $(this);
    var rating = $el.find('span').text();
    var $stars = $('<div><div class="ratings-stars"></div><div class="ratings-stars"></div><div class="ratings-stars"></div><div class="ratings-stars"></div><div class="ratings-stars"></div></div>');
    var full_stars = Math.floor(rating);
    var half_star = false;
    var remainder = rating - full_stars;

    if(remainder >= 0.25 && remainder <= 0.75) {
      half_star = true;
    } else if(remainder > 0.75) {
      full_stars += 1;
    }   

    $stars.find('div:lt('+full_stars+')').addClass('star');
    if(half_star) {
      $stars.find('div:eq('+full_stars+')').addClass('half-star');
    }

    $el.find('span').replaceWith($stars);
  });
});

CSS 我将留给你。

编辑:更新$stars为使用<div />而不是<span />

于 2011-05-31T12:39:35.347 回答