如何在PHP生成的表格中为每条记录添加对应百分比的进度条
PHP表格多行进度条仅第一条生效解决方案
问题描述
我近期在实现页面进度条功能,网上通用方案都是通过style属性传入百分比值设置进度条宽度。目前我已经可以在表格的「% Total tiempo」列计算出每条任务记录的完成百分比,希望将该百分比通过进度条可视化展示,但实现后仅第一条记录的进度条能正常显示,其余记录均不生效。
现有代码
进度条与JS代码
<br><br> <div class="barra"> <div class="progreso"><div class="porcentaje"></div></div> </div> <script type="text/javascript"> document.getElementsByClassName("progreso")[0].style.width = "<?php echo $porcentaje; ?>%"; document.getElementsByClassName("porcentaje")[0].innerHTML = "<?php echo $porcentaje; ?>%"; </script>
表格渲染PHP代码
<?php @ob_flush(); flush(); $total = substr($user->finish, 0, 4) -substr($user->start, 0, 4) + 1; $current = substr($user->diasf, 0, 4); $porcentaje = ($current/$total) * 100; $porcentaje = round($porcentaje, 0); ?> <?php @ob_flush(); flush(); usleep(500);?> <thead> <th style="" class="button-3"> 负责人</th> <th style="" class="button-4"> 任务</th> <th style="" class="button-3">描述</th> <th style="" class="button-3">分配天数</th> <th style="" class="button-3">已完成天数</th> <th style="" class="button-3">总进度占比</th> </thead> <?php foreach($users as $user){ ?> <tr> <td class="bg-info text-white" style="color:#070001"><?php echo substr($user->persona, 0, 200); ?></td> <td class="bg-info text-white" style="color:#070001"><?php echo substr($user->title, 0, 200); ?></td> <td class="bg-info text-white" style="color:#070001"><?php echo substr($user->description, 0, 200); ?></td> <td class="bg-info text-white" style="color:#070001"><?php echo substr($user->finish, 0, 200)-substr($user->start, 0, 200) + 1; ?> 天</td> <td class="bg-info text-white" style="color:#070001"><?php echo substr($user->diasf, 0, 200); ?> 天</td> <td class="bg-info text-white" style="color:#070001"> <?php $total = substr($user->finish, 0, 4) -substr($user->start, 0, 4) + 1; $current = substr($user->diasf, 0, 4); $percent = ($current/$total) * 100; $percent = round($percent, 0); ?>
问题根因
现有JS代码中使用document.getElementsByClassName("progreso")[0]选中元素,[0]固定匹配页面中第一个对应类名的元素,循环生成的其余行进度条不会被匹配处理,因此仅第一条生效。
修复方案
服务端渲染场景下不需要额外使用JS设置进度,直接在PHP循环渲染进度条时,将百分比写入元素的style属性即可,删除原有的JS代码。
在表格总进度占比列计算完$percent后,直接输出以下进度条代码:
<div class="barra"> <div class="progreso" style="width: <?php echo $percent; ?>%"> <div class="porcentaje"><?php echo $percent; ?>%</div> </div> </div>
效果对比
- 修复前:

- 修复后:

内容的提问来源于stack exchange,提问作者jose garcia
相关产品推荐
相关产品推荐

