首页 > 解决方案 > jquery中的每个函数如何对多个数字求和?

问题描述

我想对多个数字求和,但这无法与每个函数一起使用。

尝试了什么:-

totalPgCost();
function totalPgCost(){
var totalPgCost = 0;
$('.pgBookingTable tr').find('.pgCost').each(function(){
totalPgCost += $(this).val();
});
$('.totalPgCost').text(totalPgCost);
                    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


<table class="pgBookingTable">
<tr><td><span class="pgCost">10000</span></td><tr>
<tr><td><span class="pgCost">5000</span></td><tr>
<tr><td>Total <span class="totalPgCost"></span> /-</td><tr>
</table>

为什么我得到0?

答案将不胜感激!

标签: javascriptjquery

解决方案


text不需要val。html 表也没有正确平衡,因为没有关闭tr。在添加将字符串转换为数字之前

totalPgCost();

function totalPgCost() {
  var totalPgCost = 0;
  $('.pgBookingTable tr').find('.pgCost').each(function() {
    totalPgCost += parseInt($(this).text().trim(), 10);
  });
  $('.totalPgCost').text(totalPgCost);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


<table class="pgBookingTable">
  <tr>
    <td><span class="pgCost">10000</span></td>
  </tr>
  <tr>
    <td><span class="pgCost">5000</span></td>
  </tr>
  <tr>
    <td>Total <span class="totalPgCost"></span> /-</td>
  </tr>
</table>

find如果您确定只有跨度将在 thar 表中具有该类,您也可以避免

totalPgCost();

function totalPgCost() {
  var totalPgCost = 0;
  $('.pgBookingTable .pgCost').each(function() {
    totalPgCost += parseInt($(this).text(), 10);
  });
  $('.totalPgCost').text(totalPgCost);

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


<table class="pgBookingTable">
  <tr>
    <td><span class="pgCost">10000</span></td>
  </tr>
  <tr>
    <td><span class="pgCost">5000</span></td>
  </tr>
  <tr>
    <td>Total <span class="totalPgCost"></span> /-</td>
  </tr>
</table>


推荐阅读