我尝试使用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>
结果就是这些
答案 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>