我需要总结使用JavaScript通过“ foreach”功能获得的数据

时间:2018-08-08 11:19:12

标签: javascript php

我尝试使用Javascript总结通过foreach函数获得的数据,如下所述,但我失败了,有人支持p.se。

这是代码:

<tbody>  
 <?php
 $running_year = 2018;
 $count = 1;
 $query = $this->db->get('teacher')->result_array();
 foreach ($query as $row):
 ?> 

<td class="count-me">
    <?php 
    $teacher_id = $this->db->get_where('subject',
    array('teacher_id' => $row['teacher_id'],'year'=> 
    $running_year))->result_array();
    foreach ($teacher_id as $row1):?>

    <?php
    $subject_no = $this->db->get_where('class_routine', 
    array('subject_id' => $row1['subject_id']));

    $test = $subject_no->num_rows();
    echo $test;
    ?>
    </br>
    <?php endforeach;?>
</td>


<td id="countit">
  <?php                   
  $teacher_id = $this->db->get_where('subject', 
  array('teacher_id' =>$row['teacher_id'], 'year'=> $running_year))->result_array();
  foreach ($teacher_id as $row1):?>


     //I need the results (that is sum) to be here

  </br>
  <?php endforeach;;?>
 </td>

 <?php endforeach;?>

</tbody>

下面是javascript

<script>
      var tds = document.getElementsByTagName('td');
      var sum = 0;
      for(var i = 0; i < tds.length; i ++) {
      if(tds[i].className == 'count-me') {
      sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
            }
        }
      document.getElementById('countit').innerHTML += '<tr><td>' + sum + '</td><td>total</td></tr>';

    </script>

结果就是这些

p'se click here to see the result

1 个答案:

答案 0 :(得分:0)

您的代码的基本逻辑是正确的。我相信PHP响应来晚了,而javascript首先作为客户端执行。您可以尝试jquery和 $(document).ready(function()

 <script
  src="https://code.jquery.com/jquery-3.3.1.js"
  integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
  crossorigin="anonymous"></script>


    <script>

$(document).ready(function() {
          var tds = document.getElementsByTagName('td');
          console.log(tds);
          var sum = 0;
          for(var i = 0; i < tds.length; i ++) {
          if(tds[i].className == 'count-me') {
          sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
                }
            }

            alert(sum);
    });
        </script>