gpt4 book ai didi

javascript - 我怎样才能用jquery中的每个函数对多个数字求和?

转载 作者:行者123 更新时间:2023-11-29 16:31:30 25 4
gpt4 key购买 nike

我想要对多个数字求和,但这无法适用于每个函数。

尝试了什么:-

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>

如果您确定表中只有 span 具有该类,您也可以避免 find

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>

关于javascript - 我怎样才能用jquery中的每个函数对多个数字求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56034783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com