简体   繁体   English

关于使用jQuery获取表列总和的问题

[英]Issue On Getting Sum of a Table Column Using jQuery

Can you please take a look at this demo and let me know why I am not getting the sum of the . 能否请您看一下这个演示,让我知道为什么我没有得到总和。 app cells? app单元?

 var total = 0; $(".app").each(function() { total += parseInt($(this).val()); }); $("#total").html(total); 
 #total { height: 100px; width: 100px; padding: 15px; color: #fff; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table style="width:100%"> <tr> <td>Jill</td> <td>Smith</td> <td class="app">50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td class="app">94</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td class="app">94</td> </tr> </table> <br /> <div id="total"></div> 

Change parseInt($(this).val()); 更改parseInt($(this).val()); to parseInt($(this).html()); parseInt($(this).html()); as the td cells do not have any value attribute and change the color property for total to #000 (black), as the output will not be visible. 因为td单元格没有任何value属性,并且将total的color属性更改为#000 (黑色),因为输出将不可见。

 var total = 0; $(".app").each(function() { total += parseInt($(this).html()); }); $("#total").html(total); 
 #total { height: 100px; width: 100px; padding: 15px; color: #000; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table style="width:100%"> <tr> <td>Jill</td> <td>Smith</td> <td class="app">50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td class="app">94</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td class="app">94</td> </tr> </table> <br /> <div id="total"></div> 

You have to use html() : 您必须使用html()

var total = 0;
$(".app").each(function() {
    total += parseInt($(this).html());
});

$("#total").html(total);

The val() method is used to get value from form elements like inputs and selects. val()方法用于从输入和选择之类的表单元素获取值。 Docs 文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM