计算每个元素的百分比

时间:2016-03-18 20:03:10

标签: javascript jquery each percentage

我有以下代码来计算每个元素的百分比(如投票投票系统):

$(document).ready(function() {
    $("#percentage").click(function() {
        var number, sumNumbers = 0, newPercent;
    
        $(".item").each(function() {
            number = $(this).children(".itemNum").text();
            number = +number;

            sumNumbers += number;

            if(sumNumbers != 0) {
              newPercent = (number / sumNumbers) * 100;
            } else {
              newPercent = 0;
            }

            $(this).children(".percentage").text(newPercent+"%");
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="item">
  <span class="itemNum">0</span> <span class="percentage"></span>
</div>

<div class="item">
  <span class="itemNum">2</span> <span class="percentage"></span>
</div>

<div class="item">
  <span class="itemNum">1</span> <span class="percentage"></span>
</div>

<button id="percentage">Calculate Percentage!</button>

但结果是:

0 0%
2 100%
1 33.33333333333333%

那么,如何计算返回以下结果?

0 0%
2 66.66666666666667%
1 33.33333333333333%

我需要这些结果才能在我的民意调查系统上设置进度条,那么,如何做到这一点?

1 个答案:

答案 0 :(得分:3)

您需要通过 parseInt()函数将文本解析为整数。

首先需要对数字求和,然后才能计算百分比。

对于一个循环问题:
您无法在一个循环中计算百分比。解释here

&#13;
&#13;
$(document).ready(function() {
    $("#percentage").click(function() {
        var number, sumNumbers = 0, newPercent;
         $(".item").each(function(){
               number = $(this).children(".itemNum").text();
               sumNumbers += parseInt(number);
               
          });
        $(".item").each(function() {
            number = parseInt($(this).children(".itemNum").text());

            if(sumNumbers != 0) {
              newPercent = (number / sumNumbers) * 100;
            } else {
              newPercent = 0;
            }

            $(this).children(".percentage").text(newPercent+"%");
        });
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="item">
  <span class="itemNum">0</span> <span class="percentage"></span>
</div>

<div class="item">
  <span class="itemNum">2</span> <span class="percentage"></span>
</div>

<div class="item">
  <span class="itemNum">1</span> <span class="percentage"></span>
</div>

<button id="percentage">Calculate Percentage!</button>
&#13;
&#13;
&#13;