javascript - 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?
答案将不胜感激!
解决方案
你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>
推荐阅读
- python - 在方法参数中避免面包屑
- sql-server - SQL:如何将多个同名的xml节点选择成逗号分隔的列表
- c++ - 嵌入式系统的谷歌测试
- c++ - 为什么具有无用的孤立“静态”的函数被认为是不纯的?
- javascript - 如何在谷歌地图中突出显示用户的当前位置?(就像新的 google.com/maps PWA)
- laravel - Laravel - 将 Stream 与新的 Http 客户端一起使用
- python - Django 递归注解
- javascript - 根据给定条件创建嵌套 json 对象
- kotlin - 设置器不修改二维数组
- r - 如何在大矩阵中组合具有相似名称的列