-1

我正在使用 googlecharts 插件来生成柱形图。

我还想获得 td 中存在的值的平均值。是否可以通过谷歌图表插件或者任何人都可以帮助我编写 ajquery 来计算平均值。计算平均值后,我需要将其添加到“avg”类的段落标签中。谢谢您的帮助。

我的代码是:

<table id="weather">
                    <thead>
                        <tr>
                            <th></th>
                            <th>Mar</th>
                            <th>Apr</th>
                            <th>May</th>
                            <th>Jun</th>
                            <th>Jul</th>
                            <th>Aug</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <th>Weather</th>
                            <td>20</td>
                            <td>22</td>
                            <td>18</td>
                            <td>24</td>
                            <td>20</td>
                            <td>22</td>
                        </tr>
                    </tbody>
                </table>

和javascript代码:

<script type="text/javascript">
        gvChartInit();
        $(document).ready(function(){
            $('#weather').gvChart({
        chartType: 'ColumnChart',
        gvSettings: {
            width: 100,
            height: 40,
            colors:['gray'],
            hAxis: {textPosition: 'none'},
            vAxis: {minValue: 0, textPosition: 'none', gridlines: {color: '#ffffff'}},
            legend: {position: 'none'}
        }
    });
        </script>
4

3 回答 3

2

尝试这样的事情:

avg = 0, amount = 0;
$('td').each(function(){
    avg += +($(this).text());
    amount++;
});
avg /= amount;
$('.avg').text(avg);

但是您可能想确保它是正确的td,因此您可以将trid 设置为“天气”之类的东西,然后更改$('td').each()$('#weather td').each()

于 2012-12-17T17:29:01.563 回答
1

您可以使用

var avg=0;

$('#weather td').each({function(){
            avg=avg+parseInt($(this).text());
         });

avg=avg/$('#weather td').length;

或者

var avg=0;
var count=0;
   $('#weather td').each({function(){
                avg=avg+parseInt($(this).text());
                count=count+1;
             });

    avg=avg/count;

在你可以在 p 标签上添加 avg 之后

$('p.avg').html(avg);
于 2012-12-17T17:31:19.767 回答
0

这应该为您返回平均值:

var totalVal = 0,
    iCount = $('#weather').find('td').length;
$('#weather').find('td').each(function(i,val){
    totalVal = totalVal + parseInt($(val).text());
});
alert('Avg = '+totalVal/iCount);

​</p>

于 2012-12-17T17:33:10.247 回答