首页 > 解决方案 > 对值求和时的 NaN 结果

问题描述

有一个想要对值求和但得到结果的测试脚本:total:NaN(需要对除第一列之外的所有列求和。从第 2 列和第 6 列开始) 该表仅包含第 2 列和第 6 列中的数字。

代码 PHP 和脚本在同一个文件中,这是我的代码

这是脚本:

<script>
       var totals=[0,0,0,0,0];
        $(document).ready(function(){
            var $dataRows=$("#mytable tr:not('.totalColumn, .titlerow')");
            $dataRows.each(function() {
                $(this).find('.rowDataSd').each(function(i){        
                    totals[i]+=parseInt( $(this).html());
                });
            });
            $("#mytable td.totalCol").each(function(i){  
                $(this).html(totals[i]);
            });
        });
</script>

并且 php 有这个代码:

<table id="mytable">
 <thead>
 <tr class="titlerow">
 <th scope="col">Column1</th>
 <th>Column2</th>
 <th>Column3</th>
 <th>Column4</th>
 <th>Column5</th>
 <th>Column6</th>
 </tr>
 </thead>
 <tbody>
 <tr>
 <?php
 include("conn.php");

$result = mysql_query("SELECT * FROM table1 GROUP BY name");

 while($test = mysql_fetch_array($result))
 {
 $id = $test['id']; 
 echo"<td>".$test['name']."</td>";
 echo"<td class='rowDataSd'>".$test['value1']."</td>";
 echo"<td class='rowDataSd'>".$test['value2']."</td>";
 echo"<td class='rowDataSd'>".$test['value3']."</td>";
 echo"<td class='rowDataSd'>".$test['value4']."</td>";
 echo"<td class='rowDataSd'>".$test['value5']."</td>";
 echo "</tr>";
 }
 mysql_close($conn);
 echo '<tfoot>
    <tr class="totalColumn">
        <td>.</td> 
        <td class="totalCol">Total:</td> 
        <td class="totalCol">Total:</td> 
        <td class="totalCol">Total:</td> 
        <td class="totalCol">Total:</td> 
        <td class="totalCol">Total:</td> 
    </tr>
</tfoot>';
 ?>
</table>

标签: jquery

解决方案


parseInt当值不是正确的数字时返回 NaN,您可以使用以下方法清除数据:

$(this).text().replace(/[^0-9]/g, '');

推荐阅读