简体   繁体   中英

Jquery Math with Multiple HTML tables

So I have 12 tables, one for each month of the year. Each table row has a cell that displays a value. I would like to calculate the sum of these rows/cells for each table. Right now I'm using a script that looks like this from a preview answer, but to duplicate it 12 times is not working and it's a lot of code. Is there a shorter way I can do this?

 <script type='text/javascript'> //<![CDATA[ $(window).load(function(){ var valueCells = document.querySelectorAll('.rowDataSdAugust'); var sum = 0; Array.prototype.forEach.call( valueCells, function(valueCell) { sum += parseFloat(valueCell.innerText); } ); var roughsum = sum /valueCells.length; var finalsum = roughsum.toFixed(2); document.querySelectorAll('.totalColAugust')[0].innerHTML = "<h1 style='color:green;'>"+ finalsum + "% GAIN</h1>"; }); //]]> </script> <script type='text/javascript'> //<![CDATA[ $(window).load(function(){ var valueCells = document.querySelectorAll('.rowDataSdJuly'); var sum = 0; Array.prototype.forEach.call( valueCells, function(valueCell) { sum += parseFloat(valueCell.innerText); } ); var roughsum = sum /valueCells.length; var finalsum = roughsum.toFixed(2); document.querySelectorAll('.totalColJuly')[0].innerHTML = "<h1 style='color:green;'>"+ finalsum + "% GAIN</h1>"; }); //]]> </script> 

Create two arrays - one for table names and other for total column names. Then execute the same function number of times thru loop.

    <script type='text/javascript'>
//<![CDATA[

    $(window).load(function(){

        var tableArray = new Array("rowDataSdJanuary","rowDataSdFebruary","rowDataSdMarch","rowDataSdApril","rowDataSdMay","rowDataSdJune","rowDataSdJuly","rowDataSdAugust","rowDataSdSeptember","rowDataSdOctober","rowDataSdNovember","rowDataSdDecember");
        var totalColArray = new Array("totalColJanuary","totalColFebruary","totalColMarch","totalColApril","totalColMay","totalColJune","totalColJuly","totalColAugust","totalColSeptember","totalColOctober","totalColNovember","totalColDecember");

        for(i=0; i<tableArray.length; i++) {     

            var valueCells = document.querySelectorAll('.'+tableArray[i]);
            var sum = 0;

            Array.prototype.forEach.call(
                valueCells,
                function(valueCell) {
                  sum += parseFloat(valueCell.innerText);
                }
            );
            var roughsum = sum /valueCells.length;
            var finalsum = roughsum.toFixed(2);
            document.querySelectorAll('.'+totalColArray[i])[0].innerHTML = "<h1 style='color:green;'>"+ finalsum + "% GAIN</h1>";            

        }        

    });

//]]> 
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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