[英]Calculate total of values in table cells using jquery
我有一个值如下表,
<table>
<tbody>
<tr>
<td class='price'>5</td>
</tr>
<tr>
<td class='price'>NA</td>
</tr>
<tr>
<td class='price'>10</td>
</tr>
<tr>
<td class='price'>NA</td>
</tr>
<tr>
<td class='price'>20</td>
</tr>
<tr>
<td class='total'></td>
</tr>
</tbody>
</table>
我的任务是计算有效值的总和(5、10和20)并在总单元格中显示总和。 我试过的代码是
var prices = $('.price'),
total = 0;
$.each(prices, function(i, price) {
if (price != 'NA') {
total = total + price;
}
});
$('.total').text(total);
我面临的问题是,我没有得到正确的输出。 有时,表单元格包含空值而不是'NA'。 我不确定我缺少什么。 请提出建议。
使用isNaN检查单元格是否包含值,然后将其转换:
$.each(prices, function(i, price){
if (!isNaN($(this).text())){
total = total + Number($(this).text());
}});
注意:如果使用“ parseInt”,它将始终返回整数-因此,如果表中有十进制值,请使用Number(String) ,它将尝试转换所有看起来像数字的值...
您需要使用td元素的text / html并在添加之前将值解析为整数:
var prices = $('.price');
var total = 0;
$.each(prices, function(i, price){
var pc=$(this).text();
if (pc!= 'NA'){
total = total + parseInt(pc,10);
}});
$('.total').text(total);
您的代码工作正常,问题在于您将总数连接在一起,因此Use parseInt()
函数将解析字符串并返回整数。
parseInt($(this).text() , 10);
句法
parseInt(string, radix);
参数
串
要解析的值。 如果string不是字符串,则将其转换为1。 字符串中的前导空格将被忽略。
基数
2到36之间的整数,表示上述字符串的基数(数学数字系统中的基数)。 为人类常用的十进制系统指定10。 始终指定此参数,以消除读者的困惑并保证可预测的行为。 当未指定基数时,不同的实现产生不同的结果。
由于prices
是jQuery对象,因此请使用$.fn.each()
,然后需要使用$.fn.text()
来获取文本。
还可以使用parseInt()
将字符串转换为整数。
采用
var prices = $('.price');
var total = 0;
prices.each(function() {
var price = $(this).text(); //use the method to get text of cell
if (price != 'NA') {
total = total + parseInt(price, 10); //use parseInt to convert to number
}
});
$('.total').text(total);
$(document).ready(function() { var prices = $('.price'); var total = 0; prices.each(function() { var price = $(this).text(); if (price != 'NA') { total += parseInt(price, 10); } }); $('.total').text(total); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tbody> <tr><td class='price'>5</td></tr> <tr><td class='price'>NA</td></tr> <tr><td class='price'>10</td></tr> <tr><td class='price'>NA</td></tr> <tr><td class='price'>20</td></tr> <tr><td class='total'></td></tr> </tbody> </table>
创建一个捣鼓你... 小提琴
var total = 0;
$(".price").each(function (i, price) {
var price = $(this).text();
if (price != 'NA') {
total = total + parseInt(price);
}
$('.total').text(total);
});
$(document).ready(function(){
var prices = $('.price');
var total = 0;
$.each(prices, function(i, price)
{
var val=$(this).text();
if (val!="NA" && val!="")
{
total = total + parseInt(val);
}
});
$('.total').text(total);
});
这是小提琴
使用jqyery获取所有tds,使用jquery每个函数遍历所有tds,然后使用isNaN检查当前td是否包含数字。 如果是这样,则将该值求和。
var sum = 0, elText;
$('.price').each(function (index, element) {
elText = element.innerText;
isNaN(elText) || (sum += parseInt(elText));
});
$('.total').text(sum);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.